复制构造函数和赋值操作符

#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 << "构造函数Salec_item(const std::string &book)被调用了," << endl;
	}


		//复制构造函数, 是构造函数的一种,      也可以不用写,C++也直接自己写一个一样,
	Sales_item(const Sales_item &orig) :isbn(orig.isbn), units_sold(orig.units_sold), revenue(orig.revenue)
	{
		cout << "复制构造函数被调用了," << endl; // 一般函数体是空的,
	}    // 将函数orig里边的成员函数复制到类Salec_item中,


	// 赋值操作符   也可以不用写,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;
}

int main()
{
	Sales_item a;
	Sales_item b("0-123-22222-5");


	Sales_item c(b);
	a = b;

	Sales_item item = string("2-556-2222-1");

	cout << endl << "试一下foo:" << endl;
	Sales_item ret;
	ret = foo(item);

	cout << endl << "试一下vector:" << endl;
	vector<Sales_item> scec(5);

	cout << endl << "试一下数组:" << endl;
	Sales_item primer_eds[] = {
		string("0-12-45-2"),
		string("0-23-5-3"),
		Sales_item()
	};

	return 0;
}

你可能感兴趣的:(复制构造函数和赋值操作符)