关于基类和派生类的拷贝、赋值构造函数【转】 参考度4.5星

源地址:http://topic.csdn.net/u/20100618/16/f505efc3-fcdf-4ca8-a699-b26b8aa7acc4.html  #10楼

关键是意识到学习还是要自己动手主动去验证求解问题

-------------------------------------------------------------------------

当基类中“显示定义了拷贝构造函数和赋值操作符时”
当派生类中“显示定义了拷贝构造函数和赋值操作符时”
如果派生类中的拷贝和赋值构造函数中没有“显示指定基类的拷贝和赋值构造函数”,即:派生类只是把自己的成员进行了赋值

问1:当定义派生类对象时,依次使用派生类的拷贝初始化、赋值操作符时,基类的拷贝构造函数和赋值操作符会不会隐式调用?
只有基类的构造函数会自动调用,拷贝和赋值不会自动调用;派生类拷贝构造时,自动调用的是基类的构造函数而不是拷贝构造函数;
即基类的拷贝和赋值需要显式调用

问2:基类的拷贝初始化、赋值操作符的形参必须是(const 类型 &)吗?如果不是const 或 不是引用,还会隐式调用吗?
可以不是const,但不是引用不行,编译器会报错,不过你没理由不用const

#include <iostream>
using namespace std;

struct Base
{
    int a; 
    Base():a(12){cout<<"Base construct"<<endl;}
    Base (int n):a(n) {}
    //Base(const Base& b):a(b.a) {cout<<"Base copy construct"<<endl;}
    Base(Base& b):a(b.a) {cout<<"Base copy construct"<<endl;}
    //Base(Base b):a(b.a) {cout<<"Base copy construct"<<endl;}//error

    Base & operator=(const Base& b) {a=b.a;cout<<"Base operator ="<<endl;return *this;}  //原程序中漏掉return *this ,因为需要返回自身函数类型的引用
};
struct Derived:public Base
{
    int d;
    Derived():d(7){cout<<"Derived construct"<<endl;}
    Derived(int i,int j):Base(i),d(j) {}

    //Derived(Derived& b):Base(b),d(b.d){cout<<"Derived copy construct"<<endl;}  //正确 参考C++primer P488引用转换
    Derived(Derived& b):d(b.d){cout<<"Derived copy construct"<<endl;}
    //Derived& operator=(const Derived& b){d=b.d;cout<<"Derived operator ="<<endl;}
    Derived & operator=(const Derived& b){d=b.d;Base::operator=(b);cout<<"Derived operator ="<<endl;return *this;}
};

int main(void)
{
    Derived d(3,9),d1(d),d2;//此处创建d2时会调用Base()构造函数,Derived()构造函数

    cout<<d.a<<endl;
    cout<<d1.a<<endl;

    d2=d;
    cout<<d.a<<endl;
    cout<<d2.a<<endl;

    system("pause");  //system("pause")就是从程序里调用“pause”命令;而“pause”这个系统命令的功能很简单,就是在命令行上输出一行类似于“Press any key to exit”的字,等待用户按一个键,然后返回。
    return 0; }

 

 

原文地址:https://www.cnblogs.com/nkxyf/p/2597962.html