开发者

Using operator overloading in C++

class A
{
public:
    ostream& operator<<(int  string)
    {
        cout << "In Overloaded function1\n";
        cout << string 开发者_Go百科<< endl;
    }
};

main()
{
    int temp1 = 5;
    char str = 'c';
    float p= 2.22;
    A a;
    (a<<temp1);
    (a<<str);
    (a<<p);
    (a<<"value of p=" << 5);
}

I want the output to be: value of p=5

What changes should is do...and the function should accept all data type that is passed


There are 2 solutions.

First solution is to make it a template.

            template <typename T>
            ostream& operator<<(const T& input) const
            {
                    cout << "In Overloaded function1\n";
                    return (cout << input << endl);
             }

However, this will make the a << str and a << p print c and 2.22, which is different from your original code. that output 99 and 2.

The second solution is simply add an overloaded function for const char*:

            ostream& operator<<(int  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

            ostream& operator<<(const char*  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

This allows C strings and everything convertible to int to be A <<'ed, but that's all — it won't "accept all data type that is passed".


BTW, you have forgotten to return the ostream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜