2013-10-05 49 views
1

我有一類稱爲locationdata其中有一個名爲PointTwoD無法從朋友類訪問私有和公有成員

#include <string> 
#include <iostream> 

using namespace std; 

class locationdata 
{ 
    public: 
    locationdata(); //default constructor 
    locationdata(string,int,int,float,float); //constructor 

//setter 
void set_sunType(string); 
void set_noOfEarthLikePlanets(int); 
void set_noOfEarthLikeMoons(int); 
void set_aveParticulateDensity(float); 
void set_avePlasmaDensity(float); 

//getter 
string get_sunType(); 
int get_noOfEarthLikePlanets(); 
int get_noOfEarthLikeMoons(); 
float get_aveParticulateDensity(); 
float get_avePlasmaDensity(); 


float computeCivIndex(); 
friend class PointTwoD; //friend class 

    private: 

    string sunType; 
    int noOfEarthLikePlanets; 
    int noOfEarthLikeMoons; 
    float aveParticulateDensity; 
    float avePlasmaDensity; 

}; 

朋友I類有一個名爲PointTwoD另一類是假設包含類:locationdata作爲私人會員。

#include <iostream> 
#include "locationdata.h" 

using namespace std; 

class PointTwoD 
{ 
    public: 
    PointTwoD(); 
    locationdata location; // class 


    private: 
    int x; 
    int y; 

    float civIndex; 

};當我嘗試在我的main()中實例化一個PointTwoD對象,並使用函數fromn定位數據,我得到一個錯誤:請求成員'位置'在「測試」這是非類類型PointTwoD()()( )。

#include <iostream> 
#include "PointTwoD.h" 
using namespace std; 

int main() 
{ 
    int choice; 

    PointTwoD test(); 

    cout<<test.location->get_sunType; //this causes the error 
} 

我的問題是

1)爲什麼犯規我的朋友類的工作,我想我應該能夠訪問來自朋友的所有屬性使用所有功能一旦被宣佈

2)應我使用繼承而不是朋友類來訪問類PointTwoD中的所有類定位數據的方法和屬性?

首次更新:之後我改變了申報從PointTwoD測試()來PointTwoD測試,我得到以下錯誤:基礎操作「 - >」具有非指針型,這是什麼意思,以及如何解決它

+2

最煩惱的解析罷工了。 – goji

+0

由於新錯誤說,它是一個非指針類型,使用'.'運算符而不是' - >'。 – goji

回答

2

此位置:

PointTwoD test();

是一個函數聲明,而不是一個變量的定義。

您需要:

PointTwoD test;

或C++ 11:

PointTwoD test{};

更多信息,請參見http://en.wikipedia.org/wiki/Most_vexing_parse

+0

它仍然不起作用,我得到一個新的錯誤,請參考問題 – Computernerd

+0

新的錯誤意味着一個新的問題。這個問題與我們已經解決的錯誤有關。您還應該嘗試自己調試新的錯誤,以便在尋求幫助之前修復舊錯誤。 – goji