在对象定义之后调用构造函数
Calling constructor after object Definition
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的构造函数中定义的。
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素