2013-10-05 107 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