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见(二)