对该调用没有可匹配的函数重载:(student) (std::string&, int&, int&)
我正在尝试创建一个类 student 的数组,并在后续初始化:
#include <iostream>
#include <string>
using namespace std;
class student{
private:
string name;
int roll_no;
int marks;
public:
student(){
name = " ";
roll_no = 0;
marks = 0;
}
student(string a, int b, int c){
name = a;
roll_no = b;
marks = c;
}
void get(){
cout << name << "\t" << roll_no << "\t" << marks << endl;
}
};
int main(){
cout << "Enter no. of students: ";
int n;
cin >> n;
student students[n];
for(int i = 0; i < n; i++){
cout << "Enter student name: ";
string a;
cin >> a;
cout << "Enter student roll_no: ";
int b;
cin >> b;
cout << "Enter student marks: ";
int c;
cin >> c;
students[i](a, b, c);
}
for (int i = 0; i < n; i++){
students[i].get();
}
}
出于某些原因,函数调用失败,尽管参数与错误信息匹配:
no match for call to '(student) (std::string&, int&, int&)'
41 | students[i](a, b, c);
| ~~~~~~~~~~~^~~~~~~~~
我在使用一个在线编译器:一个在线编译器.
解决方案
首先,你定义了一个变长数组:
cout << "Enter no. of students: ";
int n;
cin >> n;
student students[n];
其中 n 不是常量表达式。变长数组不是C++的标准特性,尽管有些编译器可以支持它们。
在这种情况下,最好使用标准容器 std::vector 而不是数组。
其次,当数组被定义时,类型为 student 的对象已经使用该类的默认构造函数创建。
因此,在这条语句中:
students[i](a, b, c);
编译器实际上试图调用一个在类中未定义的函数运算符,因此产生错误信息。
你可以在类定义中定义该运算符,例如如下所示:
void operator ()( const std::string &name, int roll_no, int marks )
{
this->name = name;
this->roll_no = roll_no;
this->marks = marks;
}
请注意,第一参数是具有常量引用类型的参数(构造函数中也应使用相同的类型)。此外,在运算符定义之后,或在定义任何其他成员函数之后,使用分号是多余的。
或者,不使用该函数运算符,你也可以直接写成:
students[i] = {a, b, c};
同样,函数 get 应该是该类的常量成员函数,因为它不会改变被调用的对象。也就是说,可以像下面这样声明:
void get() const {
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。