2011-09-29 24 views
3

我试图超载运算符< <。我期待的输出是InitializingHello WorldOut,但它只是输出Hello World。我无法弄清楚我的代码有什么问题。谢谢你的帮助。重载I/O运算符C++

#include <iostream> 
    using namespace std; 


    ostream &operator << (ostream &out, const char* &s) 
    { 
    out << "Initializing" << s << "Out"; 
    return out; 
    } 

    void main() { 

    cout << "Hello World" << endl; 
    system("Pause"); 
    } 

回答

2

< <与原型完全相同已经出现过载。编译器不能决定使用哪一种?

+0

如果是这样,他会得到链接错误的情况。对? –

+2

原型不一样,标准的不是参考。即使它们在相同的地方,他也不会因为它们位于不同的命名空间而导致链接器错误;他会得到一个模糊的电话。 – rodrigo

+2

如果编译器无法确定,他会得到一个编译器错误。编译器不会随机选择一个... –

0

我认为既然左手侧是在std命名空间,它使用在该std命名空间,而不是您在全局命名空间中定义的功能ostream& std::operator << (ostream &out, const char* s)。如果你试图把你的名字空间放入std,你会得到一个链接错误。你唯一的真正希望是改变一方或另一方的类型,可能是通过围绕它们来包装。

struct charptr { 
    const char* ptr; 
    charptr(const char* p) :ptr(p) {} 
}; 
ostream &operator << (ostream &out, const charptr &s) 
{ 
    out << "Initializing" << s.ptr << "Out"; 
    return out; 
} 
int main() { //int main, not void 
    cout << charptr("Hello World") << endl; 
    system("Pause"); 
} 
+0

您必须使'charptr&'参数为'const'。 – sth

+0

我不认为有'std :: operator <<(ostream&out,const char *&s)'。然而,有一个'std :: operator <<(ostream&out,const char * s)'。注意第二个参数中的参考。 –

+0

是的,你们俩。 Fix'd。 –

3

"Hello World"实际上const char[12]类型,可衰变成const char *型的R值(临时)是,但你的函数需要一个参考const char*,正如你可能知道,你不能绑定对非常量r值的引用。所以你的运营商不叫,但标准的ostream &operator << (ostream &out, const char* s)是。

PS。请不要写void main()。它应该是int main(),除非你在嵌入式系统中(不太可能)。

+0

即使在嵌入式系统中,void main()也不是main的有效C++签名。 –

1

已经有一个operator<<const char*定义在标准库中,它在输出中使用。不会使用您的重载,因为临时字符串文字不能绑定到运算符第二个参数中的非const引用。

如果您删除引用或使其为const,那么您的运营商调用。它甚至不会与标准库中的相冲突,因为该函数是作为函数模板实现的。你的不是,编译器更喜欢非模板化的函数。

如果它被调用,则会导致堆栈溢出,因为out << "Initializing"会立即再次递归调用同一个运算符。

0

罗德里戈指出,一个字符串类型是const char[x],我有一个歪主意:

#include <iostream> 
using namespace std; 

template<int len> 
ostream &operator << (ostream &out, const char (&s)[len]) 
    { 
    out << ((const char*)"Initializing") << ((const char*)s) << ((const char*)"Out"); 
    return out; 
    } 

    int main() { 
    cout << "Hello World" << endl; 
    } 

http://ideone.com/7wCNy