[英]C++ External Class Implementation Not Working
I am trying to implement my own 'User' class from an external C++ file.我正在尝试从外部 C++ 文件实现我自己的“用户”class。 Therefore, I created a User.h , User.cpp and main.cpp file which are all in the same directory.
因此,我创建了一个User.h 、 User.cpp和main.cpp文件,它们都在同一个目录中。 Here you can see the source code of each file:
在这里可以看到每个文件的源代码:
./User.h ./用户.h
#include <string>
class User {
public:
User(std::string username, std::string password);
std::string getPassword();
std::string username;
private:
std::string password;
};
./User.cpp ./用户.cpp
#include "User.h"
User::User(std::string username, std::string password) {
this -> username = username;
this -> password = password;
}
std::string User::getPassword() {
return password;
}
./main.cpp ./main.cpp
#include <iostream>
#include "User.h"
int main() {
User eve("Eve3033", "Pass1234");
std::cout << eve.getPassword();
return 0;
}
The g++ compiler error: g++ 编译错误:
undefined reference to `User::User(std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>, std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>)'
C:\\Users\\wise-\\AppData\\Local\\Temp\\ccQgLvm9.o:main.cpp:(.text+0xb8): undefined reference to `User::getPassword[abi:cxx11]()' collect2.exe: error: ld returned 1 exit status
I tried to remove the std::string User::getPassword()
method, which didn't result in any compiling errors.我试图删除
std::string User::getPassword()
方法,它没有导致任何编译错误。 The construction of the User eve("Eve3033", "Pass1234")
instance was also successfull and I was able to access the public std::string username
attribute. User eve("Eve3033", "Pass1234")
实例的构建也成功了,我能够访问public std::string username
属性。
However, when I tried to implement the std::string User::getPassword()
method to also access the private std:string password
attribute, g++ returned the same error.但是,当我尝试实现
std::string User::getPassword()
方法以访问private std:string password
属性时,g++ 返回了相同的错误。
I searched for the error online and found the following links:我在网上搜索错误,找到以下链接:
Undefined reference to Class::Method() 未定义对 Class::Method() 的引用
Undefined Reference to Class::Function() in C++ C++ 中对 Class::Function() 的未定义引用
I hope you have any ideas on that problem:)我希望你对这个问题有任何想法:)
Your error must be due to a syntax error or missing file in your command.您的错误一定是由于语法错误或命令中缺少文件造成的。 Compiling this code in VS works just fine, and has the expected output. Make sure you have:
g++ main.cpp user.cpp
在 VS 中编译这段代码工作得很好,并且有预期的 output。确保你有:
g++ main.cpp user.cpp
If you need more context and examples, see here .如果您需要更多上下文和示例,请参见此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.