【问题标题】:having error while compiling with static method使用静态方法编译时出错
【发布时间】:2012-10-16 12:44:45
【问题描述】:

在我的标题上说,试图在我的代码中使用静态方法编译我的文件。 我的computeCivIndex() 正在尝试从用户那里获取 5 个输入并进行计算并返回浮点值。

this.sunType 用于 java 语法,但对于 V++,如果两者同名,我应该用什么将它们链接在一起?

我的代码中有 getter 和 setter 方法,还有 2 个构造函数,它们太长而无法发布。

这是我的错误:

test.cpp:159: error: cannot declare member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’ to have static linkage
test.cpp: In static member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’:
test.cpp:161: error: ‘this’ is unavailable for static member functions

代码:

class LocationData
{   
    private:
    string sunType;
    int noOfEarthLikePlanets;
    int noOfEarthLikeMoons;
    float aveParticulateDensity;
    float avePlasmaDensity;
    public:
    static float computeCivIndex(string,int,int,float,float);
};
static float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int     noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity)
{
    this.sunType = sunType;
    this.noOfEarthLikePlanets = noOfEarthLikePlanets;
    this.noOfEarthLikeMoons = noOfEarthLikeMoons;
    this.aveParticulateDensity = aveParticulateDensity;
    this.avePlasmaDensity = avePlasmaDensity;
    if(sunType == "Type O")
         //and more for computation
}

【问题讨论】:

    标签: c++ static-methods


    【解决方案1】:

    static 声明延迟 static 实现。静态实现意味着您的函数符号仅在实现它的文件中可用。

    只需在函数实现之前移除静态。此外,静态函数是类函数,您不能访问其中的类的非静态成员。这些是在没有对象实例的情况下使用的,因此没有实例变量。

    float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int     noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity)
    {
    }
    

    【讨论】:

      【解决方案2】:

      编译器错误对我来说似乎相当清楚:

      错误:'this' 对静态成员函数不可用

      基本上,因为成员是static,它不会在该类型的特定实例的上下文中执行——所以在方法中使用this 是没有意义的。您确实尝试使用this,因此出现错误。

      来自MSDN documentation for static

      当您在类声明中声明成员函数时,static 关键字指定该函数由该类的所有实例共享。静态成员函数无法访问实例成员,因为该函数没有隐式 this 指针。要访问实例成员,请使用实例指针或引用的参数声明函数。

      听起来您只是不想将成员声明为静态成员。

      (顺便说一句,我不喜欢说它“由类的所有实例共享”的描述 - 我更喜欢它不特定于类的任何特定实例的想法。不必有任何个实例都被创建了。)

      【讨论】:

      • 我的作业要求它必须是静态方法,那么有没有办法链接它们?
      • @HengAikHwee:听起来很奇怪。您可以更改签名以引用实例吗?您可以返回一个新实例吗?
      • 嗯,你是说LocationData数据吗?数据.sunType = sunType; ?
      • @HengAikHwee:嗯,something 就像那样——尽管名为compute... 的方法无论如何都要更改对象中的数据,这很奇怪。在不知道您要完成什么的情况下很难帮助您。你为什么要尝试使用this
      • 我试图根据来自 cin 的用户 5 个输入进行计算。将会有另一个类会触发这个计算
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 2012-10-02
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多