我试图将类分成不同的cpp文件。
我的档案是:
Source.h:
#pragma once
#include "stdafx.h"
#include <iostream>
class printData {
public:
void print(int i);
void print(double f);
void print(char* c);
};
Source.cpp:
#include "stdafx.h"
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
ConsoleApplication3.cpp:
#include "stdafx.h"
#include <iostream>
#include "Source.h"
using namespace std;
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
但是,当我尝试建立项目时,我得到了:
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(int)" (?print@printData@@QAEXH@Z) referenced in function _main
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(double)" (?print@printData@@QAEXN@Z) referenced in function _main
1>ConsoleApplication3.obj : error LNK2019: unresolved external symbol "public: void __thiscall printData::print(char *)" (?print@printData@@QAEXPAD@Z) referenced in function _main
如果我将所有文件合并到ConsoleApplication3.cpp中,则不会出现错误。
答案 0 :(得分:1)
你在这里遇到两个错误:
在.cpp文件中,您应该按如下方式定义方法:
#include "stdafx.h"
#include <iostream>
#include "Source.h"
using namespace std;
void printData::print(int i) {
cout << "Printing int: " << i << endl;
}
void printData::print(double f) {
cout << "Printing float: " << f << endl;
}
void printData::print(char* c) {
cout << "Printing character: " << c << endl;
}
不要在.cpp文件中编写此类printData等,因为它是Source.h中定义的类的另一个定义。您应该只按照上面显示的方式在.cpp文件中定义类方法。
编译器抱怨因为所有main.cpp文件看到的是一个Source.h文件,它有一个只声明但未定义的类,因为Source.cpp不包含Source.h。但即使你确实在Source.cpp中包含了Source.h,你也会因为上面给出的原因而得到一个类重新定义错误。