2012-04-06 118 views
3

为什么这项工作做得很好:ostream的deferencing运营商<<

cout << "foo"; 

虽然这不?

(&cout)->operator<<("foo"); 

所以我想这件事情来覆盖相关的IT工作正常数值。 (我正在使用MS Visual C++编译器。)

回答

7

operator<<仅作为有限数量类型的成员函数实现。对于其他类型的,它的实现为一个全球性的过载,如:

std::ostream &operator<<(std::ostream &os, T const &t) { 
    // write the data here 
} 

您使用的将只与被实现为成员函数,而不是全局重载工作的语法。

0

要获得输出为cout << "foo";,您必须超载运营商<<

1

cout有一个重载的成员函数operator<<(const void *)。这是参数"foo"的最佳匹配。 (const char*隐式转换为const void*。)因此,将会输出一个指针。

// These call std::ostream& operator<<(std::ostream &os, const char * val)  
cout << "foo"; 
operator<<(cout,"foo"); 

// This calls cout's member function operator<<(const void * val) 
(&cout)->operator<<("foo");