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;