我需要帮助为类调试此代码。我不是计算机科学专业,所以我需要用非常基本的术语来解释。我得到的错误代码是错误LNK2019:未解析的外部符号“public:void __thiscall Student :: showStudent(void)”(?showStudent @ Student @@ QAEXXZ)在函数_main中引用
我不明白这意味着什么。有人可以解释一下吗?
#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错误?求救!
答案 0 :(得分:1)
添加到AndyG的答案。您的Student
类应该继承自Person。像这样:
class Student : public Person {
/* members */
};
因为在您的学生构造函数中,您正在调用Person::Person(id, a, i);
并且这不会设置您的Student
属性idNum, age and initial
,因为您已在学生中重新定义了这些属性,而您#&# 39;重新调用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和initial),这定义了Student
是< / strong>Person
。这是面向对象编程(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
的属性。