2012-05-05 127 views
-1

我對構圖有以下代碼。它會產生一個錯誤,構圖中的構造函數調用

#include <iostream> 

using namespace std; 

class X 
{ 
     private: 
       int iX; 
     public: 
      X(int i=0) : iX(i) { cout <<"Constructing X.."<<endl; } 
      ~X() { cout <<"Destructing X.."<<endl; } 

      int getIX() { return iX; } 
}; 

class Y 
{ 
     private: 
       X x(3); 
       int jY; 
     public: 
      Y(int j = 0) : jY(j) { cout <<"Constructing Y.."<<endl; } 
      ~Y() { cout <<"Destructing Y.."<<endl; } 
      void callGetX() { cout <<"iX is "<<(x.getIX())<<endl; } 
}; 

int main() 
{ 
    Y yObj(1); 
    yObj.callGetX(); 
} 

錯誤: 在成員函數voidŸ:: callGetX() 'X' 未申報(第一次使用此功能)

是否有我錯過了什麼? 任何人都可以告訴我這個場景的構造函數調用機制嗎?

+5

你得到什麼錯誤?這是完全有效的:'X x(5);'。 – mfontanini

+1

這是不相關的問題,但'#包括''代替的#include 「iostream的」' –

+0

它說, 在成員函數voidY :: callGetX() X未申報(第一次使用此功能) –

回答

3

你把成員在初始化列表:

Y(int j = 0) : x(3), jY(j) 

你的語法:

class Y 
{ 
private: 
    X x(3); 
//... 
}; 

是非法的。

4
X x(3); 

這是不是在C++的法律(法律Java中據我所知)。事實上,它使編譯器認爲x是一個成員函數,它返回類X的對象,而不是考慮xX的成員變量。

而是做到這一點:

Y(int j = 0) : jY(j), x(3) { cout <<"Constructing Y.."<<endl; } 
+0

是的,它現在工作正常! –