重载运算符 << 可以打印出两个不同的函数吗?

Overloading operator << Possible to print out two different functions?

本文关键字:lt 两个 函数 运算符 打印 重载      更新时间:2023-10-16

这是我的代码的一小段:

Cord::Cord(int x, int y){
  x_ = x;
  y_ = y;
}
Cord::Cord(int x, int y, int z){
  x_ = x;
  y_ = y;
  z_ = z;
}
std::ostream& operator <<(std::ostream& out, Cord& x) {
  out << x.x_ << " " << x.y_ << " " << x.z_;
  return out;
}

是否可能使运算符在<lt;我的两个函数都重载了。现在,如果我只使用x和y的函数,它也会打印出z。有没有办法让<lt;当im只有x和y时,操作符打印出两个函数而不打印出z,或者这不可能吗?

您需要z_的默认值。

Cord::Cord(int x, int y){
  x_ = x;
  y_ = y;
  z_ = 0; // If 0 is a good default value for z_
}

有了默认值,其中一个解决方案可能是

std::ostream& operator <<(std::ostream& out, Cord& x) {
  if(z_!= 0)  // If 0 is your default value for z
      out << x.x_ << " " << x.y_ << " " << x.z_;
  else
      out << x.x_ << " " << x.y_;
  return out;
}

请注意,您的代码设计得不好。

更新:设计主张

阅读关于封装和多态性

部分解决方案:

Coord2d.cpp

Coord2d::Coord2d(int x, int y){
  x_ = x;
  y_ = y;
}
int Coord2d::getX(){
  return x_;
}
int Coord2d::getY(){
  return y_;
}
std::ostream& operator <<(std::ostream& out, Coord2d& coords2d) {
  out << x.x_ << " " << x.y_;
}

Coord3d.cpp

Coord3d::Coord3d(int x, int y, int z){
  x_ = x;
  y_ = y;
  z_ = z;
}
int Coord3d::getX(){
  return x_;
}
int Coord3d::getY(){
  return y_;
}
int Coord3d::getZ(){
  return z_;
}
std::ostream& operator <<(std::ostream& out, Coord3d& coords3d) {
  out << x.x_ << " " << x.y_ << " " << x.z_;
}

使用optional,您可以执行:

class Coord
{
public:
    Coord(int x, int y) : x(x), y(y) {}
    Coord(int x, int y, int z) : x(x), y(y), z(z) {}
    friend std::ostream& operator <<(std::ostream& out, const Coord& c)
    {
        out << c.x << " " << c.y;
        if (c.z) { out << " " << *c.z; }
        return out;
    }
private:
    int x;
    int y;
    boost::optional<int> z;
};

实时演示