链接 c++代码:对 `Student::Student(std::__cxx11::basic_string, std::allocator>, double) 的未定义引用
每次我构建代码时都会出现此错误。我尝试了不同的项目,但结果是一样的。它出现在vscode和CLion中;但是我在
#include <iostream>
#include <string>
using namespace std;
class Student{
private:
std::string name;
double grade;
public:
//public constructor to reach it
Student (std::string s, double g);
void setName(std::string n){
name = n;
}
void setGrade(double g){
grade = g;
}
std::string pass(){
//if grade greater than 60 print "yes" if not print "no"
return (grade > 60 ? "yes": "no");
}
void printStatus(){
cout << "name:" << name << endl;
cout << "grade: " << grade << endl;
cout << "Pass: " << pass() << endl;
cout << endl;
}
};
int main(){
Student Barrak("Barrak", 96);
Barrak.printStatus();
Barrak.pass();
return 0;
};
这就是我得到的。
PS C:\Users\barra\Desktop\ab> cd "c:\Users\barra\Desktop\ab\" ; if ($?) { g++ main.cpp -o main } ; if ($?) { .\main }
c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\barra\AppData\Local\Temp\cc1itdQl.o:main.cpp:(.text+0x54): undefined reference to `Student::Student(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double)'
collect2.exe: error: ld returned 1 exit status
PS C:\Users\barra\Desktop\ab>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您只声明了参数化构造函数
Student (std::string s, double g);
而不是定义它。因此链接器在需要时无法找到它,因此给出了上述错误。要解决这个问题,您可以添加此构造函数的定义,如下所示:
可以看到修改后的程序的输出此处。
方法 2
您还可以在类内部定义参数化构造函数,在这种情况下它将隐式内联,如下所示:
The problem is that you've only declared the parameterized constructor
Student (std::string s, double g);
but not defined it. So the linker cannot find it when needed and hence gives the mentioned error.To solve this problem you can add the definition for this constructor as shown below:
The output of the modified program can be seen here.
Method 2
You can also define the parameterized constructor inside the class in which case it will be implicitly inline as shown below: