【问题标题】:How to access the method of a class which is a private member of another class如何访问作为另一个类的私有成员的类的方法
【发布时间】:2013-10-09 08:25:35
【问题描述】:

我有 2 个课程,CLASS locationdata 是 CLASS PointTwoD 的私有成员。

类位置数据

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 的私有成员,但是我收到一个错误:'->' 的基本操作数具有非指针类型'locationdata'

这就是我访问私人成员的方式

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

}

【问题讨论】:

    标签: c++ class debugging pointers linked-list


    【解决方案1】:

    这与私有/公共无关。您正在使用指针访问运算符-&gt; 来访问类的成员;你应该改用.

    string sunType = l.get_sunType();
    

    【讨论】:

      【解决方案2】:

      这不是访问权限的问题,get_sunType() 已经是public

      l 不是指针,你可以通过. 操作符访问它

      更新:

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

      到:

       string sunType = l.get_sunType(); 
       //                ^
      

      【讨论】:

        【解决方案3】:

        运算符-&gt; 在位置数据中没有实现。 您需要使用. 运算符:

        string sunType = l.get_sunType();

        拉兹万。

        【讨论】:

          【解决方案4】:

          根据您的代码, p1 不是参考。

          试试

          p1.get_locationdata()
          

          而不是

          p1->get_locationdata()
          

          【讨论】:

          • 其实p1是一个迭代器,所以那部分是正确的。问题在于另一个 - l
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-21
          • 1970-01-01
          • 1970-01-01
          • 2013-04-02
          • 1970-01-01
          相关资源
          最近更新 更多