C++类的Constructors,Copy,Assignment,Destruction(一)

C++会有默认的构造函数(Constructors),复制函数(Copy),赋值函数(Assignment),析构函数(Destruction)


Constructors

与类名同名的函数就是构造函数

创建对象时自动调用

没有return type

不能声明为const(若为const还怎么初始化赋值)

default Constructors 是无参空实现的,如果自己写了Constructors则不会在有default Constructors

//constructor initializer list:
Sales_data(const std::string &s, unsigned n, double p):bookNo(s), units_sold(n), revenue(p*n) { }


Constructors主要用于初始化。在C++中,类成员如果没有用Constructors初始化的话,那么它的值是随机的

为什么要用Constructors做初始化?

因为引用和const必须初始化


Copy

对象的复制: 

Sales_data trans = new Sales_data(const std::string &s, unsigned n, double p):bookNo(s), units_sold(n), revenue(p*n) { };
Sales_data total = new Sales_data();
total = trans;//对象的复制


那么在total = trans;执行时其实是这样的:

total.bookNo = trans.bookNo;
total.units_sold = trans.units_sold;
total.revenue = trans.revenue; //注意能copy的都是Nonstatic member


class Foo {
public:
Foo(); // default constructor
Foo(const Foo&); // copy constructor
// ...
};

在C++primer是这么解释copy constructor的:The copy constructor is used implicitly in several circumstances. Hence, the copy constructor usually should not be explicit 复制构造函数在几种情况下隐式调用,所以一般情况下复制构造函数不是显示的。

a copy constructor is synthesized even if we define other constructors.//即使我们自定义了复制构造函数编译器还是会给我们一个默认复制构造函数

eg:

class Sales_data {
public:
// 定义复制构造函数
Sales_data(const Sales_data&);
private:
std::string bookNo;
int units_sold = 0;
double revenue = 0.0;
};
//在class外部实现复制构造函数
Sales_data::Sales_data(const Sales_data &orig):
bookNo(orig.bookNo), // uses the string copy constructor
units_sold(orig.units_sold), // copies orig.units_sold
revenue(orig.revenue) // copies orig.revenue
{ } // empty body


复制构造函数在下面几种情况也会调用:

• Pass an object as an argument to a parameter of nonreference type
• Return an object from a function that has a nonreference return type
• Brace initialize the elements in an array or the members of an aggregate class


Assignment,Destruction见(二)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值