C++中的拷贝构造函数和拷贝赋值操作符+const成员变量初始化(5)---《Effective C++》

C++中拷贝构造函数和拷贝赋值操作符,

C++中编译器可以自动生成copy 构造函数,copy operator=,析构器等函数,那么什么时候编译器无法自动生成copy 构造函数和copy operator=呢?
那么就是以下这两种情况啦:
1)引用成员变量
2)const成员变量
参看以下代码:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Hello{
public:
    //注意初始化方式,const成员变量和引用成员变量需要采用参数成员赋值,不能在内部赋值
    Hello(string s) :i(20),s(s){
    }

    void show(){
        cout << s <<" "<<i<< endl;
    }
private:
    string& s;
    const int i;
};

int main(){
    Hello hel("world");
    return 0;
}

这样的话,编译器就无法生成copy构造函数和copy operator=,自己也无法生成这两个函数。

PS:如何将拷贝构造函数和拷贝赋值操作符加以区分呢?即C++什么时候调用函数的copy构造函数,什么时候调用copy operator=呢?有一个规律是在C++对象第一次出现的时候调用copy 构造函数,第二次进行赋值的时候调用copy operator=,Hello h1(h)或者Hello h2=h,此时是copy 构造函数;如果是Hello h2,h2=h,此时调用的是copy operator=操作符,具体大家可以参考:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Hello{
public:
    Hello(){

    }
    Hello(string s):i(20),s(s){
        this->s = s;

    }
    Hello(Hello &s){
        this->i = s.i;
        this->s = s.s;
    }
    Hello& operator=(Hello& s){
        this->i = s.i;
        this->s = s.s;
        cout << "hello,发现问题在哪儿了吗!!!" << endl;
        return *this;
    }
    void show(){
        cout << s <<" "<<i<< endl;
    }
private:
    string s;
    int i;
};

int main(){
    Hello hel("world");
    Hello hel1;
    hel1 = hel;
    return 0;

}

PS:
C++中const成员变量的初始化方式:
1)通过在构造函数中,通过参数初始化列表的方式初始化;

class A{
public:
    A();
    A(int y):x(100){
        this->y=y;
    }

private:
    const int x;
    int y;
};

2)通过将const成员变量声明为static,然后加以初始化。

class A{
public:
    A(int y){
        this->y=y;
    }
private:
    const static int x;
    int y;
};
const int A::x=10;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值