C++ Operator Overloading | Find output programs | Set 5

This section contains the C++ find output programs with their explanations on C++ Operator Overloading (set 5).
Submitted by Nidhi, on July 02, 2020

Program 1:

#include <iostream>
using namespace std;

class Test {
public:
    void operator<<(string str)
    {
        cout << str << endl;
    }
};

int main()
{
    Test T1;
    T1 << "Hello world";
    return 0;
}

Output:

Hello world

Explanation:

Here, we created a class Test that contains member function to overload "<<" operator. In the main() function, we created the object T1 and call the "<<" operator to print the string "Hello world" on the console screen.

Program 2:

#include <iostream>
using namespace std;

class Test {
public:
    void operator.(string str)
    {
        cout << str << endl;
    }
};

int main()
{
    Test T1;
    T1.operator.("Hello world");
    return 0;
}

Output:

main.cpp:6:18: error: expected type-specifier before ‘.’ token
     void operator.(string str)
                  ^
main.cpp: In function ‘int main()’:
main.cpp:15:16: error: expected type-specifier before ‘.’ token
     T1.operator.("Hello world");
                ^
main.cpp:15:17: error: expected unqualified-id before ‘(’ token
     T1.operator.("Hello world");
                 ^

Explanation:

It will generate a compilation error. Because we cannot overload dot '.' operator in C++.

Program 3:

#include <iostream>
using namespace std;

class Test {
public:
    void operator>>(string str)
    {
        cout << str << endl;
    }
};

int main()
{
    Test T1;
    T1 >> "Hello world";
    return 0;
}

Output:

Hello world

Explanation:

In the above program, we created a class Test that contains member function to overload ">>" operator, we created the object T1 and call ">>" operator to print the string "Hello world" on the console screen.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.