0

When I try to create an object of class A having only parametrized Constructor in class B, I get following errors:

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.

4

1 回答 1

0

您不能为 C++ 中的类成员分配默认值。您需要定义构造函数。

class A {
    public:
    int z;
    A(int y){z = y;}
};
class B {
    public:
    int x;
    A ob; //
    B() : x(5), ob(x) {}
};
于 2013-07-04T06:51:26.413 回答