【C++ Primer 第15章】定义派生类拷贝构造函数、赋值运算符

时间:2024-03-22 20:05:02

学习资料

派生类的赋值运算符/赋值构造函数也必须处理它的基类成员的赋值

• C++ 基类构造函数带参数的继承方式及派生类的初始化

定义拷贝构造函数

【注意】对派生类进行拷贝构造时,如果想让基类的成员也同时拷贝,就一定要在派生类拷贝构造函数初始化列表中显示调用基类拷贝构造函数(当然在函数体内将基类部分的值拷贝也是可以的,只不过它是先用默认构造函数初始化后再修改的基类成员变量的值,效率比较低),否则它会调用基类的默认构造函数,而不会对基类的成员变量拷贝值,这样生成的对象,它的派生类部分和被拷贝的对象派生类部分一样,而基类部分则是默认构造函数的初始化结果。

代码例子1:

 #include <iostream>
using namespace std; class A
{
public:
A() { cout << "A default constructor" << endl; }
A(A&) { cout << "A copy constructor" << endl; }
};
class B : public A
{
public:
B() { cout << "A default constructor" << endl; }
B(B &b) { cout << "B copy constructor" << endl; }
}; int main()
{
B b;
B c = b;
return ;
}

输出结果:

【C++ Primer 第15章】定义派生类拷贝构造函数、赋值运算符

代码例子2:

 #include <iostream>
using namespace std; class A
{
public:
A() { cout << "A default constructor" << endl; }
A(A&) { cout << "A copy constructor" << endl; }
};
class B : public A
{
public:
B() { cout << "A default constructor" << endl; }
B(B &b) : A(b) { cout << "B copy constructor" << endl; }
}; int main()
{
B b;
B c = b;
return ;
}

输出结果:

【C++ Primer 第15章】定义派生类拷贝构造函数、赋值运算符

C++ 基类构造函数带参数的继承方式及派生类的初始化

在定义类的时候,会遇到基类的构造函数带参数,而子类子类构造函数不带参数,这时候如果以代码 a 的方式建立派生类则会出错。

 class A
{
public:
A(int x, int y): i(x), j(y) {}
private:
int i, j;
}; class B : public A
{
public:
B() { cout << "init B" << endl; }
};

在建立B类对象时,编译出错: 
 C:\Documents and Settings\admin\桌面\Text1.cpp() : error C2512: ‘A’ : no appropriate default constructor available

解决这个问题应该在A的构造函数中显式调用基类的带参构造函数。因为在基类中定义了带参构造函数,编译器不会提供默认构造函数。(或者可以在基类中增加一个不带参数的构造函数)这个问题将解决。 
代码 b 采用的是调用基类带参构造函数的方式:

代码 b:

 class A
{
public:
A(int x, int y): i(x), j(y) {}
private:
int i, j;
}; class B : public A
{
public:
B() A(,) { cout << "init B" << endl; }
};

通过在基类中增加一个不带参数的构造函数: 
代码 c:

 class A
{
public:
A(int x, int y): i(x), j(y) {}
A(); //不带参数的构造函数
private:
int i, j;
}; class B:public A
{
public:
B(): A(,) { cout << "init B" << endl; }
};

定义派生类赋值运算符

与拷贝和移动构造函数一样,派生类的赋值运算符也必须为其基类部分赋值。

 // Base::operator=(const Base&) 不会被自动调用
D& D::operator=(const D &rhs)
{
Base::operator=(rhs); //为基类部分赋值
//按照过去的方式为派生类的成员赋值
return *this;
}

举例说明:

 class base
{
public:
base(int initialvalue = ): x(initialvalue) {} private:
int x;
}; class derived : public base
{
public:
derived(int initialvalue): base(initialvalue), y(initialvalue) {}
derived& operator=(const derived& rhs); private:
int y;
}; 逻辑上说,derived的赋值运算符应该象这样:
derived& derived::operator = (const derived& rhs) // 错误的赋值运算符
{ // 请注意d1的base部分没有被赋值操作改变。
if (this == &rhs)
return *this;
y = rhs.y;
return *this;
} 不幸的是,它是错误的,因为derived对象的base部分的数据成员x在赋值运算符中未受影响。例如,考虑下面的代码段: void assignmenttester()
{
derived d1(); // d1.x = 0, d1.y = 0
derived d2(); // d2.x = 1, d2.y = 1 d1 = d2; // d1.x = 0, d1.y = 1
} derived& derived::operator = (const derived& rhs) // 正确的赋值运算符
{
if (this == &rhs)
return *this; base::operator = (rhs); // 调用this->base::operator=
y = rhs.y; return *this;
}