[英]while creating object of a class in another class having only parameterized Ctor “error: x is not a type”
When I try to create an object of class A having only parametrized Constructor in class B, I get following errors: 当我尝试在类B中创建仅具有参数化的Constructor的类A对象时,出现以下错误:
A ob(5); error: expected identifier before numeric constant
A ob(x); error: x is not a type
class A {
public:
int z;
A(int y){z = y;}
};
class B {
public:
int x;
A ob(5); or A ob(x);//This line is creating a problem
};
I searched for the same and got that we can solve this problem by writing 我进行了相同的搜索,发现我们可以通过编写来解决此问题
A ob;
B():ob(5);
OR
int x;
A ob;
B():ob(x); //here x will be uninitialized though
But I am thinking why it was giving error in the prior case. 但是我在想为什么在先前的案例中会出错。 Can someone explain in detail.
有人可以详细解释。 Thanks.
谢谢。
You cannot assign default value to class member in C++. 您不能为C ++中的类成员分配默认值。 You need to define constructor.
您需要定义构造函数。
class A {
public:
int z;
A(int y){z = y;}
};
class B {
public:
int x;
A ob; //
B() : x(5), ob(x) {}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.