【发布时间】:2021-03-24 04:10:29
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
class student {
private:
string sname;
float gpa;
public:
student(string name, float g = 0.0);
~student();
};
struct student {
string name;
int gpa;
void display();
};
student::student(string name, float g) { // **this is where I get the error**
cout << "student constructor is running..." << endl;
student stu;
stu.name += name;
stu.gpa = g;
}
student::~student() {
// cout << "Student No." << endl;
cout << "student destructor is running..." << endl;
}
void student::display() {
cout << "Student Name: " << name << endl;
cout << "Student GPA: " << gpa << endl;
}
这是一个学生头文件。 错误出现:没有构造函数“student::student”的实例与参数列表匹配。 我不明白为什么以及如何解决这个问题。
【问题讨论】:
-
为什么类和结构都同名?
-
我认为你不了解构造函数。您正在创建
student在学生构造函数中 的实例(并尝试使用不存在的空构造函数),而这确实是构造函数的工作。出于某种原因,您将student重新定义为struct和class,它们应该会给出自己的错误。您包括不存在的<iostrem>(尽管在创建此帖子时这可能是一个错字,因为这是编译器必须显示的致命错误)。您尝试使用stu.name,但student的第一个定义使用sname,而不是name。 -
假设
#include <iostrem>应该是#include <iostream>。如果您实际从真实代码中粘贴,它会有所帮助。如果您不实际输入,则不能拼写错误。无论如何,您的代码应该看起来像like this。 -
ODR 违规,您有 2 个类/结构
student。错误可能不会指向错误的实际原因:/
标签: c++ error-handling constructor