zoukankan      html  css  js  c++  java
  • 在构造函数中使用new时的注意事项

    果然,光看书是没用的,一编程序,很多问题就出现了--
    注意事项:
    
    1、 如果构造函数中适用了new初始化指针成员,则构析函数中必须要用delete
    2、 new与delete必须兼容,new对应delete,new[]对应delete[]
    3、如果有多个构造函数,则必须以相同的方式使用new,要么都是new,要么都是new[],因为构析函数只能有一个
    4、 应该定义一个复制构造函数,通过深度复制,将一个对象初始化为另一个对象
    5、 应该定义一个赋值运算符,通过深度复制,将一个对象复制给另一个对象
    
    #include<iostream>
    #include<cstring>
    #include<fstream>
    using namespace std;
    class String
    {
    private:
        char *str;
        int len;
        static int num_string;
    
    public:
        String();
        String(const char *s);
        String(const String &s);
        ~String();
        friend ostream& operator<<(ostream &os,String s);
        String operator=(const String &s)
        {
            if(this==&s) return *this;
    
            len=s.len;
            delete [] str;
            str=new char[len+1];
            strcpy(str,s.str);
            return *this;
        }
    };
    int String::num_string=0;
    String::String()
    {
        len=4;
        str=new char[len+1];
        strcpy(str,"C++");
        num_string++;
    }
    String::String(const char *s)
    {
        len=strlen(s);
        str=new char[len+1];
        strcpy(str,s);
        num_string++;
    }
    String::String(const String &s)
    {
        len=s.len;
        num_string++;
        str=new char[len+1];
        strcpy(str,s.str);
    }
    String::~String()
    {
        num_string--;
        delete [] str;
        printf("---  %d
    ",num_string);
    }
    ostream& operator<<(ostream &os,String s)
    {
        os<<s.str;
        return os;
    }
    int main()
    {
        String p("wwwww");
        String p1("qqqqqq");
        String p2;
        p2=p1;
        cout<<p<<endl<<p1<<endl<<p2<<endl;
        return 0;
    }
    

      

  • 相关阅读:
    js代码编写规范
    mysql数据库的水平拆分与垂直拆分
    git使用WebHook实现自动构建
    解决php
    laravel为模型中所有查询统一添加WHERE条件
    centos7+ 安装 php7.2
    nginx配置https
    git常用命令
    php如何应对秒杀抢购高并发思路
    nginx配置优化+负载均衡+动静分离详解
  • 原文地址:https://www.cnblogs.com/ziyi--caolu/p/4064994.html
Copyright © 2011-2022 走看看