#include <iostream>
using namespace std;
class object
{
private :
string s;
public :
object(string str)
:s(str)
{}
object(object &a)
:s(a.s)
{}
void operator=(object &a) //赋值运算符重载1号
{
this->s = a.s;
}
void operator=(string str) //赋值运算符重载2号
{
this->s = str;
}
string get_value() //获取对象的值(此处为对象所对应的字符串s)
{
return this->s;
}
~object() {}
};
int main()
{
object a("Hello World");
object b(a);
object c = b;
cout << a.get_value() << endl;
cout << b.get_value() << endl;
cout << c.get_value() << endl;
c = "Hello C++";
cout << c.get_value() << endl;
return 0;
}
上述代码实现了copy构造函数以及赋值运算符的重载,值得一提的是,即使你没有写copy构造函数和赋值运算符重载1号编译器也会默认生成这两个成员函数,如下(后面会说明当不需要这两个函数是怎样防止编译器为你生成这两个函数)。
#include <iostream>
using namespace std;
class object
{
private :
string s;
public :
object(string str)
:s(str)
{}
void operator=(string str) //赋值运算符重载2号(参数为字符串)
{
this->s = str;
}
string get_value() //获取对象的值(此处为对象所对应的字符串s)
{
return this->s;
}
~object() {}
};
int main()
{
object a("Hello World");
object b(a);
object c = b;
cout << a.get_value() << endl;
cout << b.get_value() << endl;
cout << c.get_value() << endl;
c = "Hello C++";
cout << c.get_value() << endl;
return 0;
}
上面两段代码的运行结果是相同的,接下来说一种可以防止编译器生成copy构造函数以及赋值运算符重载1号,这需要用到类的继承,在基类中将这两个函数设置为私有成员,便可防止编译器为其派生类生成这两个成员函数,代码如下:
#include <iostream>
using namespace std;
class parent
{
public :
parent() {}
~parent() {}
private :
parent(parent &a) {}
void operator=(parent &a) {}
};
class object : public parent
{
private :
string s;
public :
object(string str)
: s(str)
{}
void operator=(string str)
{
this->s = str;
}
string get_value()
{
return this->s;
}
~object() {}
};
int main()
{
object a("Hello World");
// object b(a);
// object c = b;
cout << a.get_value() << endl;
a = "Hello C++";
cout << a.get_value() << endl;
return 0;
}
如果去掉上述两行语句的注释,则编译器会报error: use of deleted function 'object::object(object&)'这样的错误并且用note: declared private here警告用户拷贝构造函数在这里不能调用。