重载运算符 << 可以打印出两个不同的函数吗?
Overloading operator << Possible to print out two different functions?
这是我的代码的一小段:
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;
};
实时演示
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在for循环中包含两个索引值的测试条件
- 在声明中合并两个常量"std::set"(不是在运行时)
- 如何使用OpenMP并行这两个循环