|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Overloading << and >> operators (syntax)
How do I go about coding that in the .h and .cpp files? Currently I have it all in the .h file, but this is causing problems (although the overloading works I think - doesn't give any compile errors) with other parts of the program. I was wondering how the syntax would go as far as declaring the function declaration in the .h file, but putting the actual code in the .cpp?
Last edited by homncruse : May 15th, 2003 at 10:17 PM. |
|
#2
|
|||
|
|||
|
Re: Overloading << and >> operators (syntax)
Quote:
this is pretty easily done, but the overloaded << and >> cannot be members of the class, they have to be declared friends of it. So anywhere outside of the class just declare friend ostream& operator(ostream&, cont Object&); then in the cpp file just provide the implementation |
|
#3
|
||||
|
||||
|
>> but the overloaded << and >> cannot be members of the class, they have to be declared friends of it.
Depends on what you're doing with the overloaded operators. It is entirely possible for you to declare an overloaded << without declaring it as a friend function. For instance, in the following example, I've overloaded << to add a number and return the resulting int value. BTW homncruse, this answers your question as well :) : Code:
myint.h
======
class MyInt {
private:
int val;
public:
MyInt(int init);
int operator <<(int val2);
};
myint.C
======
#include <iostream>
#include "myint.h"
using namespace std;
MyInt::MyInt(int init) {
val = init;
}
int MyInt::operator<< (int val2) {
val += val2;
return val;
}
int main(void) {
int x;
MyInt foo(4);
x = foo << 2;
cout << x << endl;
return 0;
}
|
|
#4
|
|||
|
|||
|
Thanks for the help, I've got the overloading working now, but I'm having a problem with pointers
To keep subject lines consistent with subjects (so we don't go "off-topic") I'll post that problem in a new thread here |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Overloading << and >> operators |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|