【发布时间】:2021-10-24 13:56:09
【问题描述】:
我创建了具有两个成员变量 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();
}
【问题讨论】:
-
如果错误出现在
car o3;行,那是因为构造函数需要两个参数,但没有提供。
标签: c++ oop constructor overloading operator-keyword