错误代码LNK2019

Error code LNK2019

本文关键字:LNK2019 错误代码      更新时间:2023-10-16

我需要帮助调试类的这段代码。我不是计算机科学专业的学生,所以我需要用非常基本的术语进行解释。我得到的错误代码是错误 LNK2019:函数 _main 中引用的未解析的外部符号"public: void __thiscall Student::showStudent(void)"(?showStudent@Student@@QAEXXZ

)我不明白这意味着什么。有人可以解释一下吗?

#include<iostream>
#include<string.h>
using namespace std;
//Added namespace
class Person
{
public:
char initial;
Person(const int id, const int a, const char i);
//Renamed function Person
void showPerson();
int idNum;
int age;
};
Person::Person(const int id, const int a, const char i)
{
idNum = id;
age = a;
initial = i;
};
void Person::showPerson(void)
{
cout << "Person id#: " << idNum << " Age: " << age << " Initial: " << initial;
//Added << to the correct places
}
class Student
{
public:
Student (const int id, const int a, const char i, const double gpa);
void showStudent();
double gpa;
int idNum;
int age;
char initial;
};
Student::Student(const int id, const int a, const char i, const double gradePoint)
{
Person::Person(id, a, i);
gpa = gradePoint;
};
void showStudent(Student student)
{
cout << "Student ID# " << student.idNum;
cout << " Avg: " << student.gpa << endl;
cout << "Person id#: " << student.idNum << " Age: " << student.age << " Initial: " << student.initial;
cout << endl << " Age: " << student.age << ".";
cout << " Initial: " << student.initial << endl;
};
void main()
{
Person per(387, 23, 'A');
//Put two lines into one
cout << endl << "Person..." << endl;
per.showPerson();
Student stu(388, 18, 'B', 3.8);
cout << endl << endl << "Student..." << endl;
stu.showStudent();
system("pause");
}

它给了我一个LNK2019错误?请帮忙!

添加到AndyG的答案中。您的Student类应继承自 Person。这样:

class Student : public Person {
/* members */
};

因为在 Student 构造函数中,您正在调用Person::Person(id, a, i);并且这不会idNum, age and initial设置您的Student属性,因为您在 Student 中重新定义了它们,并且您正在调用 Person ctor,而没有将其初始化为任何内容。

为了使您的代码更具凝聚力和可重用性,我将像这样定义类:

class Person {
protected:
char initial;
int idNum;
int age;
public:
Person(const int id, const int a, const char i);
void showPerson();

};

class Student : public Person {
private:
double gpa;
public:
Student (const int id, const int a, const char i, const double gpa);
void showStudent();

};

通过这种方式,您的Student实例具有Person类中的所有受保护成员属性(id、age 和初始),这定义了StudentPerson。这是面向对象编程 (OOP) 范式的一部分。

因此,您可以像这样设置学生构造函数:

Student::Student(const int& id, const int& a, const char& i, const double& gradePoint) {
idNum = id; // This works because Student inherits from Person, so it has all its attributes!
age = a;
initial = i;
gpa = gradePoint;
}; 

现在,您不应该有错误,并且您手头有一个干净、可重用的 OOP 解决方案。例如,你现在可以有一个老师,它也继承了Person(是推广),它将具有Person的属性。