为什么我收到 [错误] 没有匹配的函数来调用“car::car()”
我已经用两个成员变量 a 和 b 创建了两个类 car 对象……我想创建一个新对象,其 a 和 b 是我之前创建的对象的 a 和 b 的乘积。
#include<iostream>
using namespace std;
class car
{
private:
int a,b;
public:
car(int x,int y)
{
a=x;
b=y;
}
void showdata()
{
cout<<a<<" "<<b<<endl;
}
car add(car c) // to multiply 'a' and 'b' of both objects and assigning to a new
object
{
car temp; // new object of class car
temp.a = a*c.a;
temp.b = b*c.b;
return temp;
}
};
int main()
{
car o1(3,5);
car o2(0,7);
car o3;
o3=o1.add(o2);
o1.showdata();
o2.showdata();
o3.showdata();
}
回答
看看这个文档。
https://en.cppreference.com/w/cpp/language/default_constructor
因此,如果您定义另一个构造函数,则默认构造函数不会自动添加到您的类中。你做的。您必须手动添加默认构造函数。例如。
class car
{
public:
car() = default;
....
private:
int a = 0;
int b = 0;
}