在对象定义之后调用构造函数

Calling constructor after object Definition

本文关键字:调用 构造函数 之后 定义 对象      更新时间:2023-10-16
class first{
    int fa,fb;
    public:
        first();
        first(int x,int y);
        void display();
};
first::first():fa(0),fb(0){
       }
first::first(int x,int y):fa(x),fb(y){
}
void first::display(){
    cout<<fa<<" "<<fb;
}
class second{
    first f;
    int sa,sb;
    public:
        second();
        second(int x,int y,int a,int b);
        void display();
};
second::second():sa(0),sb(0){
}
second::second(int x,int y,int a,int b):f(x,y),sa(a),sb(b){
}
void second::display(){
    cout<<"The Numbers are ";
    f.display();
    cout<<" "<<sa<<" "<<sb<<endl;
}

如果已经有人问我这个问题,我深表歉意。

这是一个简单的代码,用于演示c++中嵌套类的工作。然而,在类second,对象f中,即使它以前已经定义过,我也可以使用second类的构造函数来调用它的构造函数。如何可能在已经定义的类实例上调用构造函数?

对象first f;second的成员。这意味着每个second都包含一个first。因此,在创建second的过程中,必须创建first。您的mem初始值设定项f(x,y)准确地指定了在创建second对象时如何创建f

当函数中定义的变量为时,可以混合不同的概念

void foo()
{
    Foobar f; // f is defined and default initialized  here
    Foobar d { 123 }; // d is defined and initialized with 123
}

并声明为CCD_ 13或CCD_

struct boo {
    Foobar f; // f is declared as member of type boo and how it will be
              // initialized will be known in boo's constructor
              // not here
    boo() {} // f is default constructed
    boo( int i ) : f { i } {} // f is initialized with i
};

在c++11中,为了让情况变得更糟,可以将参数传递给适当的字段构造函数:

struct boo {
    Foobar d { 123 };  // d would be initialized with 123 if otherwise is not set in boo's constructor
    boo( int i ) : d { i } {} // 123 is ignored and d is initialized with i
    boo() {} // d { 123 } is used
};

因此,即使将参数传递给字段,如何初始化字段也是在boo的构造函数中定义的。