1. 程式人生 > 其它 >C++(OOP)複製建構函式和賦值操作符

C++(OOP)複製建構函式和賦值操作符

技術標籤:C++c++指標

賦值建構函式

  • 如果沒有定義,C++會給我們定義
  • 使用自定義建構函式的情況: 類成員中存在指標

賦值操作符

  • 如果沒有定義,C++會給我們定義
  • 使用自定義賦值操作符的情況: 類成員中存在指標
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Sales_item
{
public:
	// 公有成員
	// 建構函式
	Sales_item():units_sold(0),revenue(0.0)
	{
		cout <<
"預設的建構函式被呼叫了" << endl; }; Sales_item(const std::string &book):isbn(book),units_sold(0),revenue(0.0){ cout << "建構函式被呼叫了" << endl; } // 賦值建構函式 // 如果沒有定義,C++會給我們定義 // 使用自定義建構函式的情況: 成員存在指標 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; 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){} NoName& operator=(const NoName &rhs){ 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"); cout << "foo()" << endl; Sales_item ret; ret = foo(item); cout << endl << "試一下vector:" << endl; vector<Sales_item> svec(5); cout << endl << "試一下array:" << endl; Sales_item primer_eds[] = { string("0-201-16789-6"), string("0-201-16789-8"), string("0-201-16789-1"), Sales_item() }; return 0; }