2015-10-27 49 views
0

这是我的一小段代码:重载操作符<<可以打印出两种不同的功能?

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

是否有可能使运营商在< <函数重载两个我的函数重载。现在,如果我只使用x和y的函数,它也会打印出z。如果im只有x和y或者是不可能的,是否有办法让打印出的两个函数都不打印出z?

+0

如何为'Cord'无论是2D *或* 3D,但不知道是哪个?这似乎从根本上不正确。 – Barry

+0

这很奇怪,你想要1类型是2d或者3d坐标,或者它总是一个3d坐标,如果它是0,你不想打印Z?这并不明确。 –

回答

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

请注意,你的代码是不是精心设计的。

UPDATE:设计命题

阅读有关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_; 
} 
+0

您如何判断Z的默认值与恰好是默认值的实际值之间的差异? –

+0

我刚开始学习C++,你会给我一些关于如何更好地设计我的代码的建议吗? – Jiberish

+0

@NeilKirk你不能说。我编辑了我的答案,提出了一个新的设计。 – AAmine

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