C++ +的运算符重载; #包括 使用名称空间std; 类立方体 { int w,l,d; 公众: 立方体(intw,intl,intd):w(w),l(l),d(d){ int getWidth()常量{return w;} int getLength()常量{return l;} int getDepth()常量{return d;} }; ostream&operator
如果你想用operator+得到两个立方体的总体积,你应该返回int而不是Cube object,你无论如何也不能用cout和Cube。你可以这样做C++ +的运算符重载; #包括 使用名称空间std; 类立方体 { int w,l,d; 公众: 立方体(intw,intl,intd):w(w),l(l),d(d){ int getWidth()常量{return w;} int getLength()常量{return l;} int getDepth()常量{return d;} }; ostream&operator,c++,operator-overloading,C++,Operator Overloading,如果你想用operator+得到两个立方体的总体积,你应该返回int而不是Cube object,你无论如何也不能用cout和Cube。你可以这样做 #include <iostream> using namespace std; class Cube { int w,l,d; public: Cube(int w, int l, int d) : w(w), l(l), d(d){} int getWidth() const {return w;}
#include <iostream>
using namespace std;
class Cube
{
int w,l,d;
public:
Cube(int w, int l, int d) : w(w), l(l), d(d){}
int getWidth() const {return w;}
int getLength() const {return l;}
int getDepth() const {return d;}
};
ostream& operator<< (ostream&os, const Cube& c)
{
os << "( " << c.getWidth() << ", " << c.getLength() << ", " << c.getDepth() << ")";
return os;
}
Cube operator+ (Cube& c1, Cube& c2)
{
int n = c1.getWidth() * c1.getDepth() * c1.getLength();
int d = c2.getWidth() * c2.getDepth() * c2.getLength();
int t = n + d;
return Cube(t);
}
int main()
{
Cube c1(3,5,9), c2(2,1,4);
cout << c1 << endl;
cout << c2 << endl;
cout << "Total Volume: " << c1 + c2;
}
你没有一个构造函数为
Cube(t)
接受一个参数,所以我猜“错误”是你忘了写一个?看看返回的Cube(t)代码>在这种情况下,您将返回什么?您的构造函数
的形式是立方体(int,int,int)
它实际上是一个立方体,而不仅仅是一个普通的长方体,为什么它有3个单独的值来表示宽度、长度和深度?它只需要一个,因为多维数据集的定义要求它们都是相同的。如果不允许我更改构造函数呢?我应该如何处理运算符重载(+)@WhozCraig@user3141403:将其更改为调用多维数据集实际具有的构造函数。有3个参数的那个。另外,通过const引用获取参数,因为它们没有被修改。如果要一直使用int,只需返回int
int operator+ (Cube& c1, Cube& c2) {
int n = c1.getWidth() * c1.getDepth() * c1.getLength();
int d = c2.getWidth() * c2.getDepth() * c2.getLength();
return n + d;
}