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

时间:2014-10-18 06:46:37

标签: c++

我无法理解我遇到的一些错误。我用驱动程序构造了一个简单的Test类。有人可以指出我所犯的错误吗?

这里我试图创建一个Test对象并将number变量设置为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

谢谢

1 个答案:

答案 0 :(得分:4)

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

Test::Test(){
}

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

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

另外,不要忘记编译和链接test.cpp。仅编译main.cpp(或任何被调用的驱动程序源文件)也可能导致此类链接错误。

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

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