C++ << 相同类型的运算符重载

标签 c++ operator-overloading ostream

我正在编写一种方法来打印 std::cout 中的一些空格,我知道还有其他方法可以使用标准库来实现相同的目标。不管怎样,我用了typedef存储空间的数量和 << 的重载运算符(operator)。但是我的重载根本没有被调用,因为我的 typedef被解释为无符号整数。

那么我该如何告诉编译器调用我的函数呢?

class MyClass {
private: 
  typedef unsigned int space_type;

public: 
  std::ostream& operator<< (std::ostream& _os, space_type _n_spaces) {
    for (int _C = 0; _C < _n_spaces; _C++) 
      _os << " ";
    return _os;
  }

  void PrintNumbers(char _a, char _b) {
    space_type spaces = 5;
    std::cout << _a << spaces << _b << std::endl;
  }
}

int main () {
  MyClass class_instance;
  class_instance.PrintNumbers('K', 'X');

  std::cin.get();
  return 0;
}

这是预期的输出:

K     X

这是我获得的输出:

K5X  // 5 is interpreted as an unsigned int, so my overloaded function 
     // isn't called, instead is called the std overloading with unsigned int

最佳答案

Typedef 不创建新类型,它只是创建现有类型的别名。可能你可以使用这样的东西:

struct SpaceType {
    int space_cnt;
};
...
std::ostream& operator<< (std::ostream& _os, SpaceType _n_spaces) {
    for (int _C = 0; _C < _n_spaces.space_cnt; _C++) 
      _os << " ";
    return _os;
  }
...  
SpaceType spaces = { 5 };
std::cout << _a << spaces << _b << std::endl;

关于C++ << 相同类型的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29450129/

相关文章:

c++ - 为什么STL<set>的重载运算符<function必须是const函数?

C++ 流日志 Objective-C 对象

c++ - 为什么将两个 int 分配给 double 时不能产生正确的值?

c++ - Objective-C 与 C++ 的应用数学算法

c++ - 单生产者多消费者循环缓冲区

c++ - 为什么 cout << 不能与重载的 * 运算符一起工作?

c++ - 覆盖类型数组的下标/运算符[]

c++ - << 运算符重写为 cout int 和 double 值

c++ - 我应该什么时候返回 std::ostream?

c++ - 使用 initializer_list 的模糊重载解析