[英]Visual Studio Code can't find the class that I've declared and defined in C++
I'm getting a linker error when I separate my class declarations and function definitions into their own files. 将类声明和函数定义分成各自的文件时,出现链接器错误。 The code gets through the compiler when all the code is in one singular .cpp file, but that's not what I'm trying to accomplish.
当所有代码都在一个单独的.cpp文件中时,代码将通过编译器,但这不是我要完成的工作。 I want to know how I can separate my code into different files.
我想知道如何将我的代码分成不同的文件。
Here is all the code. 这是所有代码。 This code runs completely fine.
这段代码运行得很好。
// main.cpp
#include <string>
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal {
private:
std::string name;
int height;
int weight;
std::string color;
public:
Animal(std::string, int, int);
};
#endif
Animal::Animal(std::string name, int height, int weight) {
this -> name = name;
this -> height = height;
this -> weight = weight;
}
int main() {
Animal dog("Spotty", 20, 50);
return 0;
}
Although, since I want to separate the code, I put the class declaration into it's own file and the function definitions into their own file, and I get this. 虽然,由于我想分离代码,所以将类声明放入其自己的文件中,并将函数定义放入其自己的文件中,然后得到了。
// main.cpp
#include <string>
#include "Animal.hpp"
int main() {
Animal dog("Spotty", 20, 50);
return 0;
}
// Animal.hpp
#include <string>
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal {
private:
std::string name;
int height;
int weight;
std::string color;
public:
Animal(std::string, int, int);
};
#endif
// Animal.cpp
#include "Animal.hpp"
Animal::Animal(std::string name, int height, int weight) {
this -> name = name;
this -> height = height;
this -> weight = weight;
}
This is the error I get when I compile the second version of main.cpp. 这是我编译main.cpp的第二个版本时遇到的错误。
main.obj : error LNK2019: unresolved external symbol "
public: __thiscall Animal::Animal(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,int)
" (??0Animal@@QAE@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HH@Z) referenced in function _mainmain.obj:错误LNK2019:无法解析的外部符号“
public: __thiscall Animal::Animal(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,int)
在函数_main中引用的((0Animal @@ QAE @ V?$ basic_string @ DU?$ char_traits @ D @ std @@ V?$ allocator @ D @ 2 @@ std @@ HH @ Z)main.exe : fatal error LNK1120: 1 unresolved externals
main.exe:致命错误LNK1120:1个未解决的外部组件
Try giving the parameters in your constructor names. 尝试在构造函数名称中提供参数。 eg
例如
Animal(std::string name, int h, int w);
The constructor doesnt do anything right now. 构造函数现在不执行任何操作。 Do you have the function in another file?
您是否在另一个文件中具有该功能?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.