C++类与对象:构造函数与拷贝控制

C++类与对象:构造函数与拷贝控制 #include iostream using namespace std; class Person { const string name; int age; char sex; public: Person():name(zhangsan){/*cout Person的无参构造 endl;*/ } Person(const string name,int age,char sex):name(name),age(age),sex(sex) { // cout Person的有参构造 endl; } ~Person() { // cout Person的析构函数 endl; } void show() { cout name name age age sex sex endl; } Person(const Person other):name(other.name)/*,age(other.age),sex(other.sex)*/ { this-ageother.age; this-sexother.sex; } Person operator(const Person other) { if(this!other) { //const string nmae 构造函数时已经初始化 this-ageother.age; this-sexother.sex; cout Person的拷贝赋值 endl; } return *this; }; }; class Stu { Person A; double *p; public: Stu():p(new double) { cout Stu的无造函数 endl; } Stu(const string name,int age,char sex,double score):A(name,age,sex),p(new double(score)) { cout Stu的有参构造 endl; } ~Stu() { delete p; cout Stu的析构函数 endl; } void show() { cout p p; cout *p *p endl; A.show(); } Stu(const Stu other):p(new double(*(other.p))),A(other.A){} Stu operator(const Stu other) { this-Aother.A; *(this-p)*(other.p); cout Stu的拷贝函数 endl; } }; int main() { // Stu t1; // t1.show(); // Stu t2(lisi,3,s,99.9); // t2.show(); Person t3(wangwu,17,m); Person t4; t4t3; t3.show(); t4.show(); Stu t5(wangwu,17,m,88.8); t5.show(); Stu t6t5; t6.show(); Stu t7(kenn,28,w,77.7); Stu t8; t8t7; t7.show(); t8.show(); return 0; }#include iostream #include cstring #include iomanip #include stdio.h using namespace std; class myString { char *str; int size; public: myString():str(new char[32]){cout myString无参构造endl;} myString(char *str):str(new char[32]) { strcpy(this-str,str); this-sizestrlen(); cout this-str endl; cout myString有参构造endl; printf(%p\n,this-str); } myString(const myString other):str(new char[32]) { strcpy(this-str,other.str); this-size other.size; cout myString拷贝构造endl; printf(%p\n,this-str); } myString operator(const myString other) { if(other!this) { strcpy(this-str,other.str); this-sizeother.size; cout myString拷贝赋值endl; printf(%p\n,this-str); } return *this; } ~myString() { delete []str; strnullptr; cout myString析构函数endl; } void show() { cout str str size size endl; } int empty() { string s1str; return s1.empty(); } int strlen() { string s1str; return s1.size(); } char at(int pos) { string s1str; return s1.at(pos); } }; int main() { myString p1; //p1.show(); char str[32]hello nihao; myString p2(str); p2.show(); myString p3p2; p3.show(); myString p4; p4p2; p4.show(); return 0; }