重载& lt; & lt;错误



我是编程新手,从传统的turbo c++迁移到VS c++ 2012,我有一个艰难的时间赶上,我想模拟TC的字符串库。但我不能使插入操作符工作在这段代码....请帮忙。你能指出我在这段代码中犯的错误吗?为什么我们要通过重载的引用返回对象。

#include<iostream>
#include<string>
namespace String
{
class string
{
   char word[100];
   int size;

public:
    string()
    {
        size=0;
    }
    string(int sz)
    {
        size=sz;
    }
    string(char *Word)
    {
        strcpy(word,Word);
        size=sizeof(*Word);
    }
    ~string()
    {
    }
    string &operator+(string Add)
    {
        strcat(word,Add.word);
        return *this;
    }
    string &operator=(char *Word)
    {
        strcpy(word,Word);
        return *this;
    }
/*
    ostream &operator<<(ostream &sout,string Show)
    {
        sout<<Show.word;
        return sout;
    }
*/
    void Show()
    {
        std::cout<<word;
    }
};
}
 void main()
{
String::string A="ABCDEF";
String::string B="GHIJK";
String::string C;
C=A+B;
C.Show();
std::cin.ignore(2);
//std::cout<<C;
}

你应该声明operator<<作为非成员函数,由于ostream将作为operator<<的第一个参数,因此用户定义类型的成员函数不能满足它。

namespace String
{
    class string
    {
        ...
        public:
            ostream& put(ostream &sout) { sout << word; return sout; }
    };
    ostream& operator<<(ostream& sout, string Show) { return Show.put(sout); }
}

输出操作符<<必须在命名空间中重载,而不是在类本身中重载,如果您希望能够像这样使用它:

cout << my_class_object;

所以,在你的类(string.h)的声明中添加这一行:

ostream &operator<<(ostream & sout,const string & Show);

然后在定义文件(string.cpp) 在您的命名空间中,而不是类本身,加上这个函数:

ostream & operator<<( ostream & out, const bigint & data )
{
    // the printing implementation
}

相关内容

最新更新