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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.