试图用C++构造简单的测试类

Trying to construct simple test class in C++

本文关键字:简单 测试类 C++      更新时间:2023-10-16

我很难理解我遇到的一些错误。我用一个驱动程序构造了一个简单的Test类。有人能指出我犯的错误吗?

在这里,我试图创建一个Test对象,并将数字变量设置为1,然后打印数字变量。

驱动程序:

#include "test.h"
#include <iostream>
using namespace std;
int main() {
    Test *myTest = new Test(1);
    cout << myTest->getNumber();
    return 0;
}

test.h

#ifndef __TEST_H__
#define __TEST_H__
class Test
{
private:
    int number;
public:
  Test();
  Test(int theNumber);
  int getNumber();
};
#endif

test.cpp

#include "test.h"
Test() {
}
Test(int aNumber) {
    number = aNumber;
}
int getNumber() {
    return number;
}

我得到的错误是

> Undefined symbols for architecture x86_64:   "Test::getNumber()",
> referenced from:
>       _main in cc8cXu6w.o   "Test::Test(int)", referenced from:
>       _main in cc8cXu6w.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status

感谢

在类外定义类成员时,应该使用类作用域。

Test::Test(){
}
Test::Test(int aNumber){
    //...
}
int Test::getNumber(){
    //...
}

另外,别忘了编译并链接test.cpp。只编译main.cpp(或调用任何驱动程序源文件)也可能导致这样的链接错误。

如果使用GCC,请使用以下命令进行构建:

g++ -o test main.cpp test.cpp