C++ 賦值號過載的拷貝建構函式程式碼筆記
阿新 • • 發佈:2018-11-11
#include <iostream> using namespace std; class A { public: A(int); //建構函式 A(const A &); //拷貝建構函式 ~A(); void print(); int *point; A &operator=(const A &); //過載使用物件引用的賦值運算子 }; A::A(int p) { point = new int; *point = p; cout<<"呼叫建構函式"<<endl; } A::A(const A &b) { *this = b; cout<<"呼叫拷貝建構函式"<<endl; } A::~A() { delete point; cout<<"呼叫解構函式"<<endl; } void A::print() { cout<<"Address:"<<point<<" value:"<<*point<<endl; } A &A::operator=(const A &b) { if( this != &b) { delete point; point = new int; *point = *b.point; } cout<<"呼叫賦值號過載"<<endl; return *this; } int main() { A x(2); A y = x; x.print(); y.print(); return 0; }