2012-05-05 129 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

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