Frage

I am kind of newbie to programming migrated from legacy turbo c++ to VS C++2012,I have a tough time catching up and i wanted to emulate the string library for TC. But i cant make the insertion operator work in this code....Please help Out. Could you tell the mistake i made in this code. And also why are we returning the object via reference for overloading.

#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;
}
War es hilfreich?

Lösung

You should declare operator<< as a non-member function, because ostream will be taken as the 1st argument for operator<<, a user define type's member function can't satisfy it.

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

    ostream& operator<<(ostream& sout, string Show) { return Show.put(sout); }
}

Andere Tipps

The output operator << has to be overloaded in the namespace, not the class itself if you want to be able to use it like so:

cout << my_class_object;

So, in the declaration of your class (string.h) add this line:

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

And then in the definition file (string.cpp) in your namespace, not the class itself, ad this function:

ostream & operator<<( ostream & out, const bigint & data )
{
    // the printing implementation
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top