1. 程式人生 > >C++運算子過載(7)

C++運算子過載(7)

賦值操作符也可以被繼承。

基類的操作符可以被子類訪問使用

例子如下

#include <iostream>
using namespace std;
//操作符能否被繼承??

class A {
public:
	A& operator=(const A& obj) {
		cout << "the = operator called!" << endl;
		return *this;
	}
};

class B: public A{
private:
	int data;

public:
	B(int data) {
		this->data = data;
	}

	void printNum() {
		cout << this->data << endl;
	}
};

int main() {
	B a(10), b(20);
	a = b;
	
	a.printNum();
	b.printNum();

	system("PAUSE");
	return 0;
}
輸出:  base class assignment operator called