Ostream Operator Overloading

I am working on trying to learn how to overload the << operator but my code keeps giving me errors. There are two errors whenever I compile in eclipse. One is invalid arguments for the line os << oper.factorial(num) . The other error is "num was not declared in this scope" on the same line. Any suggestions? (The top code is my header file, the bottom is my .cpp file)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef OPERATIONS_H_
#define OPERATIONS_H_
#include <iostream>
using namespace std;
class operations{
public:
	int num;
	int factorial(int num){
	if(num == 0)
		return 1;
	else if(num < 0)
		return -1*factorial(num*-1);
	else
		return num*factorial(num-1);

	}

	friend ostream& operator<< (ostream &os, operations &oper);
};

ostream& operator<< (ostream &os, operations &oper){
		os << oper.factorial(num);
		return os;
	}


#endif /* OPERATIONS_H_ */


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "operations.h"

using namespace std;

int main() {
	int num;
	cout << "Please enter a number" << endl;
	cin >> num;
	operations * oper = new operations();
	 oper->factorial(num);
	 cout << oper << endl;
}
Well your private member num is undefined, you never use it. So what is the factorial of ??? when you try to output? Anyways your setup is very questionable; you call the factorial function then output the factorial function so the first factorial call does pretty much nothing.


Why not simply do num = oper->factorial(num); or actually assign a value to num then
1
2
3
4
ostream& operator<<(ostream &stm, const operations &oper)
{
     return stm << num;
}


Or don't call the factorial in your main, assign a value to num, and output the factorial like you have now.
Topic archived. No new replies allowed.