您需要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:设计命题
阅读有关Encapsulation 和Polymorphism
部分解决:
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_;
}
如何为'Cord'无论是2D *或* 3D,但不知道是哪个?这似乎从根本上不正确。 – Barry
这很奇怪,你想要1类型是2d或者3d坐标,或者它总是一个3d坐标,如果它是0,你不想打印Z?这并不明确。 –