15.0k views
3 votes
Extend the functionality of cout by implementing a friend function in Number.cpp that overloads the insertion operator. The overloaded insertion operator returns an output stream containing a string representation of a Number object. The string should be in the format "The value is yourNum", where yourNum is the value of the integer instance field of the Number class.Hint: the declaration of the friend function is provided in Number.h.Ex: if the value of yourNum is 723, then the output is:

User Adocad
by
4.3k points

1 Answer

12 votes

Answer:

// In the number.cpp file;

#include "Number.h"

#include <iostream>

using namespace std;

Number::Number(int number)

{

num = number;

}

void Number::SetNum(int number)

{

num = number;

}

int Number::GetNum()

{

return num;

}

ostream &operator<<(ostream &out, const Number &n)

{

out << "The value is " << n.num << endl;

return out;

}

// in the main.cpp file;

#include "Number.cpp"

#include <iostream>

using namespace std;

int main()

{

int input;

cin >> input;

Number num = Number(input);

cout << num;

return 0;

}

Step-by-step explanation:

The main function in the main.cpp file prompts the user for the integer value to be displayed. The Number file contains defined functions and methods of the number class to set, get and display the "num" variable.

User Pinkesh Sharma
by
4.3k points