PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] How to print the objects specific member using only object name?

 August 15, 2022     c++, operator-overloading, output     No comments   

Issue

string var = "Hello";
cout << var << endl;

We get the result using only the object, without the help of a member variable. I want to implement a class that will work like string. For example:

class Test {
public:
    int x = 3;
};

Test var2;
cout << var2 << endl;

How can I get implement the class so the cout line prints the value of x without referring to it?


Solution

The std::string class has operator << overloaded, that's why when you write:

std::string text = "hello!";
std::cout << var1 << std::endl; // calling std::string's overloaded operator <<

Prints the text held by it simply.

Thus, you need to overload the << operator for the class:

class Test {
    int x = 3;
public:
    friend std::ostream& operator<<(std::ostream& out, const Test& t) {
        out << t.x;
        return out;
    }
}

// ...

Test var2;
std::cout << var2 << std::endl;


Answered By - Rohan Bari
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing