抱歉,我是C ++的新手,我有一个愚蠢的问题要问。如何从LocationDatacomputeCivIndex函数到PointTwoD类检索civIndex的值。 GET功能在这种情况下有帮助吗?

LocationData.h

class LocationData
{
  private:
    string sunType;
    int noOfEarthLikePlanets, noOfEarthLikeMoons;
    float aveParticulateDensity, avePlasmaDensity;
    static float civIndex;

  public:
    LocationData(); //default constructor

    LocationData(string, int, int, float, float); // no default constructor
    void setLocationData(string, int, int, float, float);
    void displaydata();


    static float computeCivIndex(string st, int earth, int moons, float particle, float plasma);

};


locationdataimp.cpp

float LocationData::civIndex = 0;

//convert sunType to sunTypePercentage
float LocationData::computeCivIndex(string st, int earth, int moons, float particle, float plasma)
{

    float sunTypePercent;

    if(st == "Type 0")
    {
        sunTypePercent = 80.0;
    }
    else if(st == "Type B")
    {
        sunTypePercent = 45.0;
    }
    else if(st == "Type A")
    {
        sunTypePercent = 60.0;
    }
    else if(st == "Type F")
    {
        sunTypePercent = 75.0;
    }
    else if(st == "Type G")
    {
        sunTypePercent = 90.0;
    }
    else if(st == "Type K")
    {
        sunTypePercent = 80.0;
    }
    else if(st == "Type M")
    {
        sunTypePercent = 70.0;
    }

    // calculate CIV Value
    float civNum,civNum1,civNum2,civNum3,civNum4,civNum5;

    civNum1 = sunTypePercent / 100;
    civNum2 = plasma + particle;
    civNum3 = civNum2 / 200;
    civNum4 = civNum1 - civNum3;
    civNum5 = earth + moons;

    civNum = civNum4 * civNum5;

    civIndex = civNum;
    //return civNum;
}


pointtwod.h文件

class PointTwoD
{
private:
    int xcord,ycord;
    float civIndex;
    LocationData locationdata;

public:
        PointTwoD();

        PointTwoD(int, int, string, int, int, float, float, float);

    string toString();

    void displayPointdata();

};


pointtwod.cpp

void PointTwoD::displayPointdata()
{
    PointTwoD pointtwod;
    LocationData locationdata;
    cout << "X axis: " << xcord << endl;
    cout << "Y axis: " << ycord << endl;
    cout << "civ: " << locationdata.civIndex  << endl;
    //locationdata.displaydata();
}


所以我应该包括什么或我犯了什么错误?

最佳答案

static float LocationData::civIndex;的声明表示civIndexstaticprivate(*)在LocationData中。

(*)作为默认访问修饰符

private访问权限意味着如果该类未明确允许它,则不能直接通过LocationData类型的变量访问它。您有两种选择:

1)提供公共吸气功能:

public static float LocationData::getCivIndex()
{
  return civIndex;
}


注意:您还需要在类定义中声明此函数:

class LocationData
{
  // ...
  public static float getCivIndex();
};


2)公开访问civIndex中的LocationData

不建议第二种选择,因为这将允许任何代码直接访问和修改civIndex的值,这很容易导致错误(并且在大型项目中很难找到这些类型的错误)。即使您只需要一个setter函数来设置传入的值,还是建议声明变量private,因为这会强制其他代码通过public方法,从而更容易识别在此过程中正在访问该变量的代码发生错误时进行调试。

您可以像这样使用选项1):

LocationData locationData;
locationdata.getCivIndex();


甚至没有类型LocationData的变量,因为该变量在该类中是静态的:

LocationData::getCivIndex();

09-27 08:51