C++派生类的拷贝构造函数、拷贝赋值运算符

1. 派生类的拷贝构造函数

  • 如果基类有定义默认构造函数,则派生类的拷贝构造函数默认会调用基类的默认构造函数初始化基类部分

  • 如果基类没有定义默认构造函数,则派生类必须在成员初始化列表中,显式调用基类相应的构造函数来初始化基类部分

  • 例子

    // 基类
    class B {
    private:
    	int b;
    
    public:
    	//B(): b(-1) {}
    	B(int v): b(v) {}
    	B(const B &ob): b(ob.b) {}
    	
    	int get_b() const {
    		return b;
    	}
    };
    
    // 派生类
    class D : public B {
    private:
    	int d;
    
    public:
    	D(int b, int v): B(b), d(v) {}
    	D(const D &od) : B(od) {			// 显式调用基类的构造函数 B(const B &ob)
    		d = od.d;
    	}
    
    	void show_msg() const {
    		std::cout << "b=" << get_b() << ",d=" << d << std::endl;
    	}
    };
    
    int main() {
    	D o1(1, 10);
    	D o2(o1);
    	
    	o2.show_msg();
    }
    

    结果:b=1,d=10


2. 派生类的拷贝赋值运算符

派生类的拷贝赋值运算符需要显式调用基类的拷贝赋值运算符来完成基类部分的拷贝赋值;否则,派生类只会拷贝赋值派生类部分,而不会包括基类部分!如,

class B {
private:
	int b;

public:
	//B(): b(-1) {}
	B(int v): b(v) {}

	B(const B &ob): b(ob.b) {}

	B& operator=(const B &ob) {
		std::cout << "B operator=" << std::endl;
		b = ob.b;
		return *this;
	}

	int get_b() const {
		return b;
	}
};


class D : public B {
private:
	int d;

public:
	D(int b, int v): B(b), d(v) {}
	D(const D &od) : B(od) {
		d = od.d;
	}

	D& operator=(const D &od) {
		B::operator=(od);			// 显式调用基类的拷贝赋值运算符
		std::cout << "D operator=" << std::endl;
		d = od.d;
		return *this;
	}

	void show_msg() const {
		std::cout << "b=" << get_b() << ",d=" << d << std::endl;
	}
};

int main() {
	D o1(1, 10);
	D o2(100, 1000);

	o2 = o1;
	
	o2.show_msg();
}

结果:
B operator=
D operator=
b=1,d=10

如果注释掉类D中拷贝赋值运算符的第一行,则结果为:
D operator=
b=100,d=10

猜你喜欢

转载自blog.csdn.net/fcku_88/article/details/88525208