链接两个文件之间的错误c ++

时间:2017-04-22 04:44:10

标签: c++

我试图从我定义的另一个类调用类函数computeCivIndex(),但是它说有一个未定义的对LocationData :: computeCivIndex(string,int,int,float,float)的引用,并且定义了一个未使用的我的LocationData.cpp中的funciton computeCivIndex(string int,int,float,float) 我使用g ++ -Wall -W LocationData.h LocationData.cpp PointTwoD.h PointTwoD.cpp MissionPlan.cpp -o myProg.o进行编译。

LocationData.h

/login

LocationData.cpp

static float computeCivIndex( string sunType_, int noOfEarthLikePlanets_, int noOfEarthLikeMoons_, float aveParticulateDensity_, float avePlasmaDensity_ ); /*calculate the possibility of life in the star system*/
};

MissionPlan.cpp

static float computeCivIndex( string sunType_, int noOfEarthLikePlanets_, int noOfEarthLikeMoons_, float aveParticulateDensity_, float avePlasmaDensity_ )
{
    int sunTypePercent = 0;
    float civIndex;
    // convert string suntype to suntype percent
    if (sunType_ == "Type O")
    {
        sunTypePercent = 30;
    }
    if (sunType_ == "Type B")
    {
        sunTypePercent = 45;
    }
    if (sunType_ == "Type A")
    {
        sunTypePercent = 60;
    }
    if (sunType_ == "Type F")
    {
        sunTypePercent = 75;
    }
    if (sunType_ == "Type G")
    {
        sunTypePercent = 90;
    }
    if (sunType_ == "Type K")
    {
        sunTypePercent = 80;
    }
    if (sunType_ == "Type M")
    {
        sunTypePercent = 70;
    }
    //compute the CivIndex
    civIndex = ( (sunTypePercent/100) - (aveParticulateDensity_ + avePlasmaDensity_)/200 ) * 
        (noOfEarthLikePlanets_ + noOfEarthLikeMoons_);
    return civIndex;
}

1 个答案:

答案 0 :(得分:0)

那是因为你还没有实现这个功能!

您需要在实现中适当地限定函数,以告诉编译器您实际上正在实现类函数:

SomeClass.h:

class SomeClass
{
    void someFunction();
    static void someStaticFunction();
};

SomeClass.cpp:

void SomeClass::someFunction() { }
void SomeClass::someStaticFunction() { } // static must not be repeated!

如果你只是

void someFunction() { }
static void someStaticFunction() { }

在命名空间范围内定义两个附加函数,而不是按照预期在类范围内定义。通过将它们声明为静态,您还可以在其定义的.cpp文件中限制可访问性,因此在编译其他.cpp文件时无法找到它。

请注意,类中的静态具有与全局范围完全不同的含义(以及函数体中的另一种不同含义) - 稍后会出现这种情况。首先,另一个错误:

locData[i].computeCivIndex(suntype,earthlikeplanets, earthlikemoons , partdensity, plasdensity);

通过运营商。 (或者operator->指针),你只能调用非静态函数(这与Java不同),静态函数需要用类范围调用:

LocationData::computeCivIndex(suntype,earthlikeplanets, earthlikemoons, partdensity, plasdensity);

static在不同范围的含义:

class SomeClass
{
    static void f(); // static class function as you know
};

static void anotherF(); // free/global function - static limits accessibility!

void yetAnotherF()
{
    static int n = 0; // see below
}

static void anotherF();是限制可访问性的C方式 - C ++变体是将函数放入匿名命名空间:

namespace
{
    void anotherF() { }
}

最后:函数中的static:这样,您声明了某种只能在函数内访问的全局变量。它仅在您第一次调用该函数时初始化,并且之前的值将在所有后续调用中可用:

void f()
{
    static int x = 0;
    printf("%d ", ++x);
}
int main()
{
    f();
    f();
    f();
    return 0;
}

输出将是:1 2 3。 您可以找到更多详细信息here