:对`testClass :: sum()'的未定义引用

时间:2017-11-07 10:40:08

标签: c++

#include<iostream>
using namespace std;

class testClass
{
public:
    int sum();
    //Postcondition: Returns the sum of the 
    //               private data members.
    void print();
    //Prints the values of the private data members.
    testClass();
    //default constructor
    //Postcondition: x = 0; y = 0;
    testClass(int a, int b);
    //Constructor with parameters
    //Initializes the private data members to the
    //values specified by the parameters.
    //Postconditon: x = a; y = b
private:
    int x;
    int y;
};

int sum() 
{
    int a, b, total;
    total = a + b;
    return total;
}

void print()
{
    cout<< "sum = " << sum() << endl;
}
testClass::testClass()
{
    x = 0;
    y = 0;
}

testClass::testClass(int a, int b)
{
    x = a;
    y = b;
}

这个程序编译100%没问题,但是当我运行它时,我收到以下错误: --------------------配置:mingw5 - CUI Debug,Builder类型:MinGW ------------------- -

检查文件依赖性... 链接... [错误] C:\ Dev-Cpp \ MAlikChapter1 \ Exercise14.cpp:56:未定义引用testClass::sum()' [Error] C:\Dev-Cpp\MAlikChapter1\Exercise14.cpp:58: undefined reference to testClass :: print()' [错误] collect2:ld返回1退出状态

完成Make Exercise14:3个错误,0个警告

int main()
{
    int m, n;
    testClass mySum;
    testClass myPrint;
    mySum.sum();

    myPrint.print();
}

这是一个示例程序来自:Malik“使用C ++的数据结构”

1 个答案:

答案 0 :(得分:4)

在函数testClass::sum的名称之前添加print在课外实现它们时:

int testClass::sum() 
{
    // ...
}
void testClass::print()
{
    // ...
}

这将解决未定义的引用错误,但您的sum函数中有另一个错误。您在未初始化变量的情况下声明本地ab变量,然后在表达式a + b中使用它们。要么用某些东西初始化它们,要么如果你想对班级成员xy求和,那么使用这些变量而不是ab,它们将在以后可用添加testClass::