[英]How to create parameterized constructor of a class in another class as a data member?
In below example, 在下面的示例中,
class Car
{
private:
int sides;
public:
Car()
{
cout<<"\ndefault called constructor";
}
Car(int nsides)
{
cout<<"\ncalled constructor";
sides=nsides;
}
};
class Auto
{
private:
Car ch;
public:
Auto(int a) : Car(a)
{
//Car test(5);
}
};
int main()
{
Auto at(5);
return 0;
}
After referring below links :- 参考以下链接后:-
create objects in object passing variables through constructor 在通过构造函数传递变量的对象中创建对象
http://www.cplusplus.com/forum/beginner/9746/ http://www.cplusplus.com/forum/beginner/9746/
I tried to write the same and execute it.unfortunately I am getting following compiler error :- 我试图编写相同的代码并执行它。不幸的是,我收到以下编译器错误:-
check.cpp: In constructor ‘Auto::Auto(int)’:
check.cpp:44: error: type ‘Car’ is not a direct base of ‘Auto’
If solution mentioned in the given links are correct then what wrong in my code ? 如果给定链接中提到的解决方案是正确的,那么我的代码有什么问题呢? My next query is ...why only parametrized constructor() throws compiler if try to initialize it without using initialization list. 我的下一个查询是...如果尝试不使用初始化列表进行初始化,那么只有参数化的builder()会抛出编译器。
This will throw compiler error :- 这将引发编译器错误:
class Auto
{
private:
Car ch(5);
public:
Auto(int a)
{
}
};
But this does not :- 但这不是:-
class Auto
{
private:
Car ch;
public:
Auto(int a)
{
}
};
Please help me in understanding this behaviour. 请帮助我理解这种行为。
Thanks in advance. 提前致谢。
In your example you are specifying by your constructor Auto(int a) : Car(a)
that Auto is derived from Car, and that's what the compiler complains about. 在您的示例中,您由构造函数Auto(int a) : Car(a)
Auto是从Car派生的,而这正是编译器所抱怨的。
To initialize your Car object (inside of Auto), do this Auto(int a) : ch(a)
. 要初始化Car对象(在Auto内部),请执行以下Auto(int a) : ch(a)
。 You put the type instead of the member's name. 您输入类型而不是成员的姓名。
About your second question, in-class member initialization is a new feature brought by C++11. 关于第二个问题, 类内成员初始化是C ++ 11带来的新功能。 You may use it by adding the parameter -std=c++11
to your compiler (GCC or Clang, msvc doesn't support it). 您可以通过在编译器中添加参数-std=c++11
来使用它(GCC或Clang,msvc不支持它)。 See this question . 看到这个问题 。 In your case you can use it as chris pointed out : 克里斯指出,您可以使用它:
class Auto {
// ...
Car ch{5};
int someVal = 5;
// ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.