簡體   English   中英

在僅具有參數化的Ctor的另一個類中創建一個類的對象時,“錯誤:x不是類型”

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM