简体   繁体   English

在仅具有参数化的Ctor的另一个类中创建一个类的对象时,“错误:x不是类型”

[英]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.

相关问题 另一个类中的参数化对象初始化 - parameterized object initialization in another class 在另一个类声明中创建一个类的对象时出现“预期类型说明符”错误 - “Expected a type specifier” error when creating an object of a class inside another class declaration 在另一个类中创建类对象 - Creating class object in another class 在仅具有参数化构造函数的类中,vptr(虚拟指针)在哪里初始化? - where is the vptr (virtual pointer) initialized in a class having only parameterized constructors? C++:在另一个 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6DZ 中初始化参数化 class 的 object - C++: Initialising an object of a parameterized class inside another class 创建派生类的对象时给出错误的抽象类 - Abstract class giving error while creating object of derived class 通过复制派生类的另一个对象来创建派生类的对象时,调用基类的副本构造函数 - Calling copy constructor of base class while creating object of derive class by copying another object of derive class 错误当创建一个不能在堆栈上只能在堆上创建其对象的类时? - Error While creating a class whose object cant be created on stack but only on Heap? 创建类对象时出错 - Error creating a class object 在C ++中的另一个类中使用未声明类的对象时出错 - Error while using an object of undeclared class in another class in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM