c++ - 如何访问属于另一个类的私有(private)成员的类的方法

标签 c++ class debugging pointers linked-list

我有 2 个类,CLASS locationdata 是 CLASS PointTwoD 的私有(private)成员。

类位置数据

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();


 static float computeCivIndex(string,int,int,float,float);
 friend class PointTwoD;

private:

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

};

类 PointTwoD

  class PointTwoD
{
  public:
  PointTwoD();
  PointTwoD(int, int ,locationdata);

  void set_x(int);
  int get_x();

  void set_y(int);
  int get_y();

  void set_civIndex(float);
  float get_civIndex();

  locationdata get_locationdata();



  bool operator<(const PointTwoD& other) const
 {
  return civIndex < other.civIndex;
 }

  friend class MissionPlan;

private:
  int x;
  int y;
  float civIndex;
  locationdata l;

};

在我的主要方法中,我试图访问 locationdata 的私有(private)成员,但是我收到一个错误:'->' 的基操作数具有非指针类型'locationdata'

这就是我访问私有(private)成员的方式

int main()
{
   list<PointTwoD>::iterator p1 = test.begin();
   p1 = test.begin();

  locationdata l = p1 ->get_locationdata();
  string sunType = l->get_sunType(); // this line generates an error

}

最佳答案

这与私有(private)/公共(public)无关。您正在使用指针访问运算符 -> 来访问类的成员;你应该使用 . 代替:

string sunType = l.get_sunType();

关于c++ - 如何访问属于另一个类的私有(private)成员的类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19266680/

相关文章:

debugging - 如何单步执行 MATLAB 调试器中的函数调用?

c++ - Init() 的返回类型冲突

java - 将文本转换为可执行语句

class - 在PowerShell 5中是否可以为类声明通用属性?

Java { Object a = new Object(); 之间的区别a.getVariable() } 和 { new Object().getVariable() }

debugging - 麻烦调试 NSTimer

c++ - 正在更改的 SFML TCP 数据包

c++ - 制作一个安装程序,在安装后安装工具栏

python - 在实例方法中更改类实例

c - 使用 gdb 64bit 越界检查内存