[英]while creating object of a class in another class having only parameterized Ctor “error: x is not a type”
当我尝试在类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
};
我进行了相同的搜索,发现我们可以通过编写来解决此问题
A ob;
B():ob(5);
OR
int x;
A ob;
B():ob(x); //here x will be uninitialized though
但是我在想为什么在先前的案例中会出错。 有人可以详细解释。 谢谢。
您不能为C ++中的类成员分配默认值。 您需要定义构造函数。
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.