【问题标题】:no instance of overloaded function matches the specified type (C++)没有重载函数的实例与指定的类型匹配(C++)
【发布时间】: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 重新定义为structclass,它们应该会给出自己的错误。您包括不存在的&lt;iostrem&gt;(尽管在创建此帖子时这可能是一个错字,因为这是编译器必须显示的致命错误)。您尝试使用stu.name,但student 的第一个定义使用sname,而不是name
  • 假设#include &lt;iostrem&gt; 应该是#include &lt;iostream&gt;。如果您实际从真实代码中粘贴,它会有所帮助。如果您不实际输入,则不能拼写错误。无论如何,您的代码应该看起来像like this
  • ODR 违规,您有 2 个类/结构 student。错误可能不会指向错误的实际原因:/

标签: c++ error-handling constructor


【解决方案1】:

编译器将学生视为结构, 更改学生结构名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2019-07-16
    • 2013-11-17
    相关资源
    最近更新 更多