-2

I have a number class and in the main method i created a pointer to a number object. This object has a string field which contains the value of the number as a string. I'm trying to print that string value with cout but i keep failing. I'm a beginner and i got deep in overloading << operator and stuff but i couldn't find a way too print the pointer,thanks..

Number *n1 = new Number();
cout<<*n1;            // That must print the string value

Edit : I can write a function to print a number object but it's not the deal. Also i'm familiar with the number->value syntax. I guess what i need to do is overload the << operator to print a pointer to object

İbrahim Akar
  • 159
  • 1
  • 14

2 Answers2

3

In c++ you can overload all kind of operators, etc. +, ++, -, --, ... You can also overload << to do whatever you want it to do.

For your example you can do following:

In class definition put

class Number
{
public:
    std::string value;
    friend ostream& operator<<(ostream& os, const Number& num);
}

and then define function however you want. For example:

ostream& operator<<(ostream& os, const Number& num)
{
    os << num.value;
    return os;
}

After that operator << on object from class Number will print value saved in string value.

For more informations you can look into: http://en.cppreference.com/w/cpp/language/operators

laky55555
  • 37
  • 5
0

Assuming your Number class looks like that:

class Number
{
public:
    std::string value;
};

Then you can print value with :

Number* n1 = new Number();
std::cout << n1->value;
shrike
  • 4,449
  • 2
  • 22
  • 38