构造函数的初始化列表

图片alt

图片alt

基本类型和传统相同,存在的意义:为了内嵌对象成员的初始化,内嵌对象在嵌入对象的构造函数执行之前就完成调用。

图片alt

图片alt

在Action构造函数执行之前,必须调用Time的构造函数

#include <iostream>
class Time
{
private:
    int hour_;
    int minute_;
    int second_;
public:
    Time();
    Time(int hour,int minute,int second);
    ~Time();
};
Time::Time(){}
Time::Time(int hour,int minute,int second)
{
    std::cout<<"Time被构造"<<std::endl;
    hour_ = hour;
    minute_ = minute;
    second_ =second;
}
Time::~Time()
{
}
class Action
{
private:
    Time time;
public:
    Action(int hour,int minute,int second);
    ~Action();
};
Action::Action(int hour,int minute,int second):time{20,50,60}
{
    std::cout<<"Action被构造"<<std::endl;
    // time = Time{10,20,50};
}
Action::~Action()
{
}
int main(){
    Action action{10,20,50};
    return 0;
}
// Time被构造
// Action被构造

对象拷贝与匿名对象

Circle c1;      //调用Circle的默认ctor
Circle c2(5.5); //调用Circle的有参ctor
Circle c3{5.5}; // 直接列表初始化,调有参ctor
Circle c4 = {5.5}; // 拷贝列表初始化,调ctor
auto c5 = Circle{2.}; // auto类型推断
decltype(c1) c6;      // decltype类型推断
int main() {
  Circle c1 = Circle{1.1};
  auto c2 = Circle{2.2}; // 用匿名对象做拷贝列表初始化
  Circle c3{};           // 直接列表初始化,调默认Ctor
  c3 = Circle{3.3};      // 用匿名对象赋值
  cout << "Area is " << Circle{4.2}.getArea() << endl;
  cout << "Area is " << Circle().getArea() << endl;  // 不推荐
  cout << "Area is " << Circle(5).getArea() << endl; // 不推荐
  return 0;
}

拷贝构造函数

声明拷贝构造函数

Circle (Circle&);
Circle (const Circle&);

调用拷贝ctor

Circle c1( 5.0 );
Circle c2( c1 );    //c++03
Circle c3 = c1;     //c++03
Circle c4 = { c1 }; //c++11
Circle c5{ c1 };    //c++11

赋值构造函数

A& operator= (const A& a);		//赋值构造函数
class A {
public:
    int* x;
    int y;
    A() = default;
    A (const A& a) {
        printf ("拷贝构造\n");
        this->x = a.x;
        this->y = a.y;
    }
    A& operator= (const A& a) {
        printf ("赋值构造\n");
        this->x = a.x;
        this->y = a.y;
    }
    A (int t) {
        x = new int (0);
        y = t;
        printf ("address: %x, point: %x, value: %d\n", this, x, y);
    }
    ~A() {
        printf ("delete %x\n", this);
    }
};
A f () {
    A ret (3);
    printf ("stack address: %x, point: %x, value: %d\n", &ret, ret.x, ret.y);
    return ret;
}

c++的成员变量是在堆还是栈区

成员变量并不能决定自bai身的存储空间位du置。决定存储位置的对象的创建方式。