重载赋值运算符(=),用于创建一个对象,比如拷贝构造函数。
/*** evaluate.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I: " << inches << endl; } Distance operator=(const Distance &D) { feet = D.feet; inches = D.inches; } }; int main() { Distance D1(11,10), D2(5,11); cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance : "; D2.displayDistance(); D1 = D2; cout << "First Distance : "; D1.displayDistance(); return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190809$ g++ evaluate.cpp -o evaluate
exbot@ubuntu:~/wangqinghe/C++/20190809$ ./evaluate
First Distance : F: 11 I: 10
Second Distance : F: 5 I: 11
First Distance : F: 5 I: 11