重载运算符<<可以打印出两种不同的功能吗?

时间:2015-10-27 19:06:30

标签: c++ operator-overloading overloading

这是我的代码的一小部分:

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;&lt;我的两个函数重载的函数。现在,如果我只使用x和y的函数,它也打印出z。有没有办法使&lt;&lt;当我只有x和y或不可能时,操作员打印出两个函数而不打印z?

2 个答案:

答案 0 :(得分:0)

您需要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;
}

请注意,您的代码设计不合理。

更新:设计主张

了解EncapsulationPolymorphism

部分解决方案:

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_;
}

答案 1 :(得分:0)

使用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;
};

Live Demo