//复制构造函数和赋值操作符 #include <iostream> #include <string> #include <vector> using namespace std; class Sales_item{ public: //普通构造函数 Sales_item(const std::string &book): isbn(book),units_sold(0), revenue(0.0) { cout << "构造函数Sales_item(const std::string &book)被调用了!" << endl; } Sales_item():units_sold(0), revenue(0.0) { cout << "默认构造函数被调用了!" << endl; } //默认构造函数 //复制构造函数,如果没写,C++会自动写,一般是const类型,传递的是引用,把传递进来的数据成员复制给当前的对象 Sales_item(const Sales_item &orig):isbn(orig.isbn), units_sold(orig.units_sold), revenue(orig.revenue) { cout << "复制构造函数被调用了!" << endl; } //赋值操作符,如果没写,C++会自动写 Sales_item& operator=(const Sales_item &rhs){ cout << "赋值操作符被调用了!" << endl; isbn = rhs.isbn; units_sold = rhs.units_sold; revenue = rhs.revenue; return *this; } private: std::string isbn; //书号 unsigned units_sold; double revenue; }; Sales_item foo(Sales_item item){ //传值方式,调用复制构造函数 Sales_item temp; //局部变量,调用默认构造函数 temp = item; //赋值操作符 return temp; // } class NoName{ public: NoName() :pstring(new std::string), i(0), d(0) {} //复制构造函数 NoName(const NoName& other): pstring(new std::string(*(other.pstring))), i(other.i), d(other.d) { cout << "NoName Copy Constructor" << endl; } NoName& operator=(const NoName &rhs){ //复制指针指向的字符串 cout << "NoName的赋值操作符" << endl; pstring = new std::string; *pstring = *(rhs.pstring); i = rhs.i; d = rhs.d; return *this; } private: std::string *pstring; //指针成员 int i; double d; }; int main() { NoName x, y; NoName z(x); //调用复制构造函数 x = y; //调用复制操作符 Sales_item a; //调用默认构造函数 Sales_item b("0-201-78345-X"); Sales_item c(b); //调用复制构造函数 a = b; //调用赋值操作符 Sales_item item = string("9-999-99999-9"); //调用构造函数Sales_item(const std::string &book) cout << endl << "试一下foo:" << endl; Sales_item ret; //调用默认 ret = foo(item); //调用复制构造函数 cout << endl << "试一下vector:" << endl; //使用容器 vector<Sales_item> svec(5); cout << endl << "试一下数组:" << endl; Sales_item primer_ede[] = { string("0-201-16487-6"), string("0-201-54848-8"), string("0-201-82470-1"), Sales_item() }; std::cout << endl << "Hello, World!" << std::endl; return 0; }
输出:
NoName Copy Constructor
NoName的赋值操作符
默认构造函数被调用了!
构造函数Sales_item(const std::string &book)被调用了!
复制构造函数被调用了!
赋值操作符被调用了!
构造函数Sales_item(const std::string &book)被调用了!
试一下foo:
默认构造函数被调用了!
复制构造函数被调用了!
默认构造函数被调用了!
赋值操作符被调用了!
赋值操作符被调用了!
试一下vector:
默认构造函数被调用了!
默认构造函数被调用了!
默认构造函数被调用了!
默认构造函数被调用了!
默认构造函数被调用了!
试一下数组:
构造函数Sales_item(const std::string &book)被调用了!
构造函数Sales_item(const std::string &book)被调用了!
构造函数Sales_item(const std::string &book)被调用了!
默认构造函数被调用了!
Hello, World!