在C中阅读有关复制构造函数和复制赋值运算符之后,我尝试创建一个简单的例子.虽然下面的代码段显然是有效的,但我不知道我是否正确地执行拷贝构造函数和拷贝赋值运算符.如果有任何错误/改进或更好的例子来了解相关概念,请问你能指出一点.
class Foobase { int bInt; public: Foobase() {} Foobase(int b) { bInt = b;} int GetValue() { return bInt;} int SetValue(const int& val) { bInt = val; } }; class Foobar { int var; Foobase *base; public: Foobar(){} Foobar(int v) { var = v; base = new Foobase(v * -1); } //Copy constructor Foobar(const Foobar& foo) { var = foo.var; base = new Foobase(foo.GetBaseValue()); } //Copy assignemnt operator Foobar& operator= (const Foobar& other) { if (this != &other) // prevent self-assignment { var = other.var; base = new Foobase(other.GetBaseValue()); } return *this; } ~Foobar() { delete base; } void SetValue(int val) { var = val; } void SetBaseValue(const int& val) { base->SetValue(val); } int GetBaseValue() const { return(base->GetValue()); } void Print() { cout<<"Foobar Value: "<<var<<endl; cout<<"Foobase Value: "<<base->GetValue()<<endl; } }; int main() { Foobar f(10); Foobar g(f); //calls copy constructor Foobar h = f; //calls copy constructor Foobar i; i = f; f.SetBaseValue(12); f.SetValue(2); Foobar j = f = z; //copy constructor for j but assignment operator for f z.SetBaseValue(777); z.SetValue(77); return 1; }