问题描述
在下面的代码中,类B的成员类型为类A(varA1).我想创建一个B类对象,其中的成员varA1打算使用A类中的非默认构造函数A(int v1).
In the code below, class B has a member that is of type class A (varA1). I want to create a class B object where the member varA1 is intended to use the non-default constructor A(int v1) in class A.
#include <iostream>
using std::cout; using std::endl; using std::string;
class A {
public:
A() { cout << "A default constructor" << endl;}
A(int v1);
private:
int var1;
};
A::A(int v1) {
cout << "A int constructor" << endl;
var1 = v1;
}
class B {
public:
B() { cout << "B default constructor" << endl;}
B(int v1);
private:
int var1;
A varA1;
};
B::B(int v1) {
cout << "B int constructor" << endl;
var1 = v1;
A varA1(int v1);
}
int main()
{
A TestA(1);
B TestB(1);
return 0;
}
但是,当我运行上面的代码时,我得到以下输出:
However when I run the code above I get the following output:
A int constructor
A default constructor
B int constructor
我在这里一定做错了.我需要更改什么,以便B类在A类中使用非默认构造函数A(int v1)?
I must be doing some wrong here. What do I need to change so that the B class uses the non-default constructor A(int v1) in class A?
我正在使用ubuntu 14.04LTS.GNU G ++ 4.9和5.1给出了相同的结果.
I am using ubuntu 14.04LTS. Both GNU G++ 4.9 and 5.1 gave the same results.
在此先感谢您的阅读和回答.
Thanks in advance for reading and answering.
推荐答案
使用成员初始化列表:
B::B(int v1) : var1(v1), varA1(v1) {
cout << "B int constructor" << endl;
}
请注意,成员的初始化(构造)顺序与在类中声明的顺序相同,因此,在成员初始化列表中切换顺序不会改变构造发生的顺序(希望编译器会警告您这个的).如果您尝试从 var1
构造 varA1
,并且在类中的 varA1
之后声明了 var1
,则此小细节就变得很重要.定义.
Note that members are initialized (constructed) in the same order that they're declared in the class, so switching orders in the member initialization list won't change the order in which construction happens (and hopefully your compiler will warn you of this). This little detail becomes important if you try to construct varA1
from var1
and var1
is declared after varA1
in the class definition.
顺便说一句,所有这行代码都在(在 B :: B(int v1)
构造函数内部)中完成:
And by the way, all this line does (inside the B::B(int v1)
constructor):
A varA1(int v1);
正向声明一个名为 varA1
的函数,该函数接受一个 int
参数并返回一个 A
对象.这与最令人烦恼的解析半类似,尽管实际上并非如此最烦人的解析.
is forward declare a function named varA1
that takes an int
parameter and returns an A
object. This is semi-similar to the most vexing parse, though this isn't really a case of the most vexing parse.
这篇关于调用C ++默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!