C ++<

时间:2015-04-04 18:44:47

标签: c++ operator-overloading ostream

我正在编写一种方法来打印std::cout中的一些空格,我知道还有其他方法可以使用标准库来实现相同的目标。无论如何,我使用typedef来存储空格数和<<运算符的重载。但是我的重载根本没有被调用,因为我的typedef被解释为unsigned int。

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

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

2 个答案:

答案 0 :(得分:2)

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

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;

答案 1 :(得分:1)

由于您将space_type定义为别名(即typedef)而非类型,因此无法与int区分,编译器将发出错误如果您试图超载operator(std::ostream&, int)

但你正在做的是定义一个类成员:

std::ostream& operator<< (std::ostream& _os, space_type _n_spaces)

当您将运算符定义为类成员时,运算符的第一个参数(隐式)是该类的实例。因此原则上,只能通过以下方式调用:

MyClass m;
m << ???

但这是一个问题:使用中缀表示法调用的运算符函数只能有两个参数,而在成员运算符函数的情况下,第一个参数是隐式的。 m << x只能由MyClass::operator<<(decltype(x))实施。

简而言之,您只能使用非成员operator<<实现此操作,并且该重载的第二个参数必须是用户类型。所以以下内容将正常工作:

struct space_t {
   unsigned x;
   space_t(unsigned x) : x(x) {}
   operator unsigned() const { return x; }
};

std::ostream& operator<< (std::ostream& os, space_t n) {
  for (unsigned i = 0; i < n; ++i) os << " ";
  return os;
}

ideeone

上查看