【问题标题】:Operator '<' and multiple values with get function, not returning运算符'<'和具有get函数的多个值,不返回
【发布时间】:2020-09-14 14:19:09
【问题描述】:

我想与操作员 '

我也不知道如何在函数GetBox()中返回多个值,我该如何解决?我想分别返回宽度、高度和深度。

下面是代码:

#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 &lt; 返回 Box 而不是 truefalse 没有意义。
  • 你想从哪个函数返回多个值?解决这个问题的方法可能会有所不同。
  • 请解释你想要operator&lt;意思对于Box
  • @Yksisarvinen 看看他的 GetBox 方法。
  • 哦,对了。 std::array&lt;int, 3&gt; 作为返回类型将是一个选项,但此时你为什么不直接将 widthheightdepth 公开?这些成员已经暴露了。

标签: c++ operator-keyword


【解决方案1】:

正如你所说, operator

bool operator&lt;(const Box &amp;other) const;

如果你想比较体积,你应该创建一个函数,它返回计算的体积:

int getVolume() const { return width * height * depth; }

这样,你就可以轻松实现比较器功能了:

bool Box::operator<(const Box &other) const {
    return getVolume() < other.getVolume();
}

不,你不能从一个函数返回多个值。如果你想这样做,你需要定义一个包含多个值的结构并返回该结构的实例。

【讨论】:

  • 我想单独返回宽度、高度和深度,所以似乎我与结构有关?我会尝试这个比较,如果我有任何其他问题,我会告诉你。
  • 如果要单独返回这些,最好实现getWidth、getHeight和getDepth方法。虽然只用一行代码完成所有事情可能很诱人,但它实际上在大多数用例中削弱了代码的可读性。
  • 是的,对每个尺寸单独使用get方法是非常不切实际的,你能用宽度、高度和深度的结构更新这个GetBox方法吗?然后为所有 3 个值返回该结构。我将不胜感激。
  • 为什么?做什么更实用:auto dimensions = box.GetBox(); int width = dimensions.width; 对此? int width = box.getWidth();您请求的东西实际上会使您的代码复杂化。
  • 要明确的是,没有办法实现Pythonic:w, h, d = box.getDimensions();
猜你喜欢
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多