运算符 '<' 和具有 get 函数的多个值,不返回
Operator '<' and multiple values with get function, not returning
我想使用运算符“<”,但我不知道这个问题的解决方案是什么。我要实现
运算符“<”(布尔类型)的一个动作,用于比较两个盒子的体积。我如何得到这个结果?
我也不知道如何在函数 GetBox() 中 return 多个值,我该如何解决?我想单独 return 宽度、高度和深度。
下面是代码:
#include<iostream>
using namespace std;
class Box{
private:
int width;
int height;
int depth;
public:
Box():width(0),height(0),depth(0){};
Box(int w, int h, int d):width(w),height(h),depth(d){};
void BoxVolume();
void SetBox(int w1,int h1,int d1);
int GetBox();
friend ostream& operator<<(ostream &exit,const Box &A);
Box operator<(Box&);
};
void Box::SetBox(int w1,int h1,int d1){
width=w1;
height=h1;
depth=d1;
}
int Box::GetBox(){
return width,height,depth;
}
void Box::BoxVolume(){
cout<<"Volume: "<<width*height*depth<<endl;
}
ostream& operator<<(ostream &exit, const Box &B){
Box temp2;
exit<<B.width<<" "<<B.height<<" "<<B.depth<<" "<<endl;
return exit;
}
Box Box::operator<(Box &K){
}
int main(){
Box Box1;
cout<<"Details about first box:"<<endl;
Box1.SetBox(1,3,5);
Box1.GetBox();
cout<<Box1;
Box1.BoxVolume();
cout<<endl;
Box Box2;
cout<<"Details about second box:"<<endl;
Box2.SetBox(2,4,6);
Box2.GetBox();
cout<<Box2;
Box2.BoxVolume();
}
正如您所说,operator< 应该 return 布尔值,因此函数签名应该是:
bool operator<(const Box &other) const;
如果你想比较体积,你应该创建一个函数,returns 计算体积:
int getVolume() const { return width * height * depth; }
有了它,你就可以轻松实现比较器功能了:
bool Box::operator<(const Box &other) const {
return getVolume() < other.getVolume();
}
不,您不能 return 来自函数的多个值。如果你想这样做,你需要定义一个包含多个值的结构和该结构的 return 实例。
我想使用运算符“<”,但我不知道这个问题的解决方案是什么。我要实现 运算符“<”(布尔类型)的一个动作,用于比较两个盒子的体积。我如何得到这个结果?
我也不知道如何在函数 GetBox() 中 return 多个值,我该如何解决?我想单独 return 宽度、高度和深度。
下面是代码:
#include<iostream>
using namespace std;
class Box{
private:
int width;
int height;
int depth;
public:
Box():width(0),height(0),depth(0){};
Box(int w, int h, int d):width(w),height(h),depth(d){};
void BoxVolume();
void SetBox(int w1,int h1,int d1);
int GetBox();
friend ostream& operator<<(ostream &exit,const Box &A);
Box operator<(Box&);
};
void Box::SetBox(int w1,int h1,int d1){
width=w1;
height=h1;
depth=d1;
}
int Box::GetBox(){
return width,height,depth;
}
void Box::BoxVolume(){
cout<<"Volume: "<<width*height*depth<<endl;
}
ostream& operator<<(ostream &exit, const Box &B){
Box temp2;
exit<<B.width<<" "<<B.height<<" "<<B.depth<<" "<<endl;
return exit;
}
Box Box::operator<(Box &K){
}
int main(){
Box Box1;
cout<<"Details about first box:"<<endl;
Box1.SetBox(1,3,5);
Box1.GetBox();
cout<<Box1;
Box1.BoxVolume();
cout<<endl;
Box Box2;
cout<<"Details about second box:"<<endl;
Box2.SetBox(2,4,6);
Box2.GetBox();
cout<<Box2;
Box2.BoxVolume();
}
正如您所说,operator< 应该 return 布尔值,因此函数签名应该是:
bool operator<(const Box &other) const;
如果你想比较体积,你应该创建一个函数,returns 计算体积:
int getVolume() const { return width * height * depth; }
有了它,你就可以轻松实现比较器功能了:
bool Box::operator<(const Box &other) const {
return getVolume() < other.getVolume();
}
不,您不能 return 来自函数的多个值。如果你想这样做,你需要定义一个包含多个值的结构和该结构的 return 实例。