我试图从类文件运行一个函数,但它不工作,我收到以下错误消息:错误LNK1120:1未解析的外部
错误LNK2019:函数_main中引用的未解析的外部符号“public:void __thiscall NS :: Class1 :: test(void)”(?test @ Class1 @ NS @@ QAEXXZ)
//Main.cpp
#include<iostream>
#include<string>
#include<Windows.h>
#include "Class1.h"
int main(){
NS::Class1 E;
E.test();
return 0;
};
//Class1.cpp
#include <Windows.h>
#include <string>
namespace NS{
class Class1{
Class1(){
OutputDebugString(L"Created.");
}
void test(){
OutputDebugString(L"Hello World");
}
};
}
//Class1.h
#ifndef _Class1_H_
#define _Class1_H_
namespace NS{
class Class1{
public:
void test();
};
}
#endif
3 回答
在源文件中,您将重新定义类,而不是定义其成员函数 . 这将给出未定义的行为,因为您只允许定义一次类 . 源文件看起来应该更像:
您还需要修改标头中的类定义,因为它不会声明构造函数 .
此外,请确保您的项目正在编译和链接两个源文件 .
您的头文件包含包含保护的保留ID,并且错过了构造函数的声明 . 它应该如下所示:
该类的定义不应该包含
class
声明,它应该include
它,并且看起来应该更像这样:我认为您的.cpp文件可能会导致此问题 . 由于您已使用类成员声明在头中创建了类定义,因此只需在Class1.cpp文件中导入Class1.h标头,然后定义成员函数,然后定义它们的行为 .
所以也许试试: