//输出 9 22 5 #include <iostream> using namespace std; class Sample { public: int v; Sample(int n){ v = n ; } Sample(){ } Sample(const Sample & a){ v = a.v + 2; } }; void PrintAndDouble(Sample o) { cout << o.v; cout << endl; } int main() { Sample a(5); Sample b = a; PrintAndDouble(b); //注意这里调用了复制构造函数 Sample c = 20; PrintAndDouble(c); //注意这里调用了复制构造函数 Sample d; d = a; cout << d.v; //本来是5,用printanddouble输出就多了2 return 0; }
//先输出123 然后输出 m,n #include <iostream> using namespace std; class A { public: int val; A(int a){ val = a; } A(){ val = 123; } A & GetObj(){ return *this; //返回 GetObj成员函数 作用的对象 } }; int main() { int m,n; A a; cout << a.val << endl; while(cin >> m >> n) { a.GetObj() = m; cout << a.val << endl; a.GetObj() = A(n); cout << a.val<< endl; } return 0; }
//重载 ”=“ 给复数赋值 #include <iostream> #include <cstring> #include <cstdlib> using namespace std; class Complex { private: double r,i; public: void Print() { cout << r << "+" << i << "i" << endl; } Complex operator=(const char* a){ string s = a; int pos = s.find("+",0); //从0号开始查找“+“的位置 string sTmp = s.substr(0,pos); // 不考虑“” 从第0位开始截取长度为pos的字符串 此处pos=1 r = atof(sTmp.c_str()); string sTmp1 = s.substr(pos+1,s.length()-2-pos); // 从pos+1位开始截取s.length-2-pos长度的字符串 此处为1
//封闭类对象的初始化 #include <iostream> #include <string> using namespace std; class Base { public: int k; Base(int n):k(n) { } }; class Big { public: int v; Base b; Big(int n):v(n),b(n){ //直接调用成员对象的类型转换构造函数 } }; int main() { int n; while(cin >>n) { Big a1(n); Big a2 = a1; cout << a1.v << "," << a1.b.k << endl; cout << a2.v << "," << a2.b.k << endl; } }
//复制构造函数 和 析构函数 在临时对象生成时的作用 #include <iostream> using namespace std; class Apple { public: static int nTotalNumber; //全局变量 Apple(){ nTotalNumber ++; //无参初始化的时候 总数加一 } ~Apple(){ nTotalNumber --; //临时变量消失时 总数也减一 } static void PrintTotal() { cout << nTotalNumber << endl; } }; int Apple::nTotalNumber = 0; Apple Fun(const Apple & a) { a.PrintTotal(); return a; } int main() { Apple * p = new Apple[4]; //无参构造函数调用4次 Fun(p[2]); //Fun函数的返回值是Apple类型的临时对象,消失时使得总数减一 Apple p1,p2; //无参构造函数调用两次 Apple::PrintTotal (); //4-1+2 delete [] p; //5-4 p1.PrintTotal (); return 0; }
i = atof (sTmp1.c_str()); return *this; } }; int main() { Complex a; a = "3+4i"; a.Print(); a = "5+6i"; a.Print(); return 0; }