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

: undefined reference to `testClass::sum()'

本文关键字:引用 sum 未定义 testClass      更新时间:2023-10-16
#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 调试,生成器类型:MinGW

--------------------

正在检查文件依赖关系...连接。。。[错误]C:\Dev-Cpp\MAlikChapter1\Exercise14.cpp:56: 未定义对testClass::sum()' [Error] C:Dev-CppMAlikChapter1Exercise14.cpp:58: undefined reference to testClass::p rint()'[错误] collect2:ld 返回 1 个退出状态

完成制作练习14:3 个错误,0 个警告

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

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

类外实现函数时sumprint函数的名称前添加testClass::

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

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