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

来源:互联网 发布:淘宝网韩版女童装 编辑:程序博客网 时间:2024/03/29 02:40

复制构造函数的适用情况

  1.对象的定义形式 - 复制初始化

  2.形参与返回值

 3.初始化容器

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


//复制构造函数
Sales_item(const Sales_item &orig)
:isbn(orig.isbn),
units_sold(orig.units_sold),
revenue(orig.revenue)
{
cout << "复制构造函数被调用" << endl;
}


//赋值操作符
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)
{
cout << endl;
Sales_item temp;
temp = item;
return temp;


}


int main()
{
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 << "====================="<<endl;
Sales_item ret;


ret = foo(b);
cout << endl<<"vetor=============" << endl;
vector<Sales_item> svec(5);


cout << endl<<"数组=============" << endl;
Sales_item primer[] = {
string("9-999-99999-1"),
string("9-999-99999-2"),
string("9-999-99999-93"),
Sales_item()
};
return 0;

0 0
原创粉丝点击