Examples for C++ note (5)
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class foo {
public: foo(int i) { cout << "Constructing." << endl; member = i; } foo(const FOO& other) { cout << "Copy constructing." << endl; member = other.member; } ~foo() { cout << "Destructing." << endl; } int get() { return member; }
private: int member; };
void display(foo obj) { cout << obt.get() << endl; }
foo get_foo() { int value; cout << "Input an integer: "; cin >> value; foo obj(value); return obj; }
|
1 2 3 4 5 6 7 8 9
| int main() { foo obj1(15); foo obj2 = obj1; display(obj2); obj2 = get_foo(); display(obj2);
return (0); }
|
返回:隐式调用复制构造
Example 2
返回:复制策略:拷贝构造函数自定义