So I'm trying to overload the << operator. I have defined in my header file as follows:
&operator<<(std::ostream &o, const gVector3 &v)
And I've defined it in my cpp file like this:
std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){
return o << "The vector elements are" << v[0] << v[1] << v[2];
}
I get the following error message. Does anyone know why?
C:\Qt\Tools\QtCreator\bin\Homework1\gVector3.cpp:112: error: 'std::ostream& gVector3::operator<<(std::ostream&,
const gVector3&)' must take exactly one argument
std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){
Your help is very much appreciated!
^
You've put the declaration inside a class definition, which for the compiler means that it's a member function - operators as class members can only take one argument. The other argument is the object you'll be calling it on. Example for easier understanding:
struct Foo {
void operator<<(int) { }
};
int main()
{
Foo f;
f << 5;
// can be also called like this:
f.operator<<(5);
}
What you need is a friend specifier to tell the compiler that you're declaring a non-member:
friend std::ostream& operator<<(std::ostream &o, const gVector3 &v)
Another example this time with non-member:
struct Foo {
friend void operator<<(Foo, int) { }
};
int main()
{
Foo f;
f << 5;
// this time, it can be called like this:
operator<<(f, 5);
}
This is assuming the operator needs access to gVector3s private data. If not, drop friend and declare it outside the class.
Related
I tried to create simple class and to overload some of it's operators, however, i failed at the very beginning, here's my code:
#include <iostream>
class Person
{
char *firstName;
char *lastName;
int age;
friend std::ostream &operator<<(std::ostream &, const Person &);
public:
Person() : firstName("Piotr"), lastName("Tchaikovsky"), age(10) {}
Person(char* f, char* l, int a)
{
this->firstName = f;
this->lastName = l;
age = a;
}
std::ostream &operator<<(std::ostream& out, const Person &p)
{
out << p.firstName << " " << p.lastName;
return out;
}
};
int main()
{
Person a;
getchar();
getchar();
}
So, before i created this operator overloading function i used debugger to see if constructor is going to work, and it worked, since default values were given correctly to the variable a i created, after that, all i did was that i created function that overloads the operator << and it is a friend function of my class, since i am taught that it is a good thing to do due to the type of the first parameter of overloading function, however, when i try to run this (NOTE: i have not tried to print out anything yet, i wanted to check if everything works fine first) it gives me errors saying:
"too many parameters for this operator function",
"binary 'operator <<' has too many parameters" and
" 'Person::operator<<' :error in function declaration; skipping function body"
however, i can't find any problems with function declaration, and i cannot possibly see how two parameters can be too many for this function. Any help appreciated!
You declare the friend function as a global non-member function. Then you define a member function.
Move the definition of the operator<< function to outside the class:
class Person
{
...
friend std::ostream &operator<<(std::ostream &, const Person &);
...
};
std::ostream &operator<<(std::ostream& out, const Person &p)
{
out << p.firstName << " " << p.lastName;
return out;
}
Or alternatively define the friend function inline:
class Person
{
...
friend std::ostream &operator<<(std::ostream &, const Person &)
{
out << p.firstName << " " << p.lastName;
return out;
}
...
};
I have the simple setup:
#include<iostream>
class Stuff {};
ostream &operator<<(ostream &lhs, const Stuff &rhs) {
return lhs << "something";
}
int main() {
Stuff stuff;
cout << stuff << endl;
cin.get();
}
where the operator<< function prints the mockup Stuff class to an ostream. What I would like to do though is move that function into the Stuff class itself. As in:
class Stuff {
ostream &operator<<(ostream &lhs, const Stuff &rhs) {
return lhs << "something";
}
};
For the life of me though, I can't figure out how to get this to work. I get the sense that I'm trying to re-define a left associative operator from the right side. Is there any way to do this properly?
The way you've defined it, that function would be a member of Stuff, so if it was allowed in C++ you'd have to call it like this:
Stuff stuff;
stuff.operator<<(std::cout, stuff);
So you don't want that.
A binary operator (like <<) takes two arguments (called operands). If it's a (non-static) member function then it must be a member function taking one parameter, where the left operand is the object that you call the function on, and the right operand is the function parameter. So you could do this:
struct Stuff {
std::ostream& operator<<(std::ostream& o) { return o << something; }
};
Stuff s;
s << std::cout << std::endl;
But you probably don't want that either!
To write std::cout << s the operator must either be a member of the left operand or must be a non-member function, so you cannot make it a member of Stuff.
Maybe what you're trying to do is this:
class Stuff {
friend std::ostream& operator<<(std::ostream& lhs, const Stuff& rhs) {
return lhs << "something";
}
};
A friend function is not a member function, so this is valid.
I have a problem with creating an operator<< in a class in this particular situation. I have a class that wraps a std::ostream so I can do some preprocessing for some types or some conditions before passing to the ostream, and want to pass some things straight through. I don't want to inherit the std::ostream, unless there is a good argument that I should. (I think I tried it once and found great difficulty and no success.)
I cannot use a template function because the processing depends on type in some cases, and I think the ambiguity would remain between it and those for my specific types (like 'Stuff'). Do I have to resort to using typeid ??
class MyClass
{
private:
std::ostream & m_out;
public:
MyClass (std::ostream & out)
: m_out(out)
{}
MyClass & operator<< (const Stuff & stuff)
{
//...
// something derived from processing stuff, unknown to stuff
m_out << something;
return *this;
}
// if I explicitly create operator<< for char, int, and double,
// such as shown for char and int below, I get a compile error:
// ambiguous overload for 'operator<<' on later attempt to use them.
MyClass & operator<< (char c)
{
m_out << c; // needs to be as a char
return *this;
}
MyClass & operator<< (int i)
{
if (/* some condition */)
i *= 3;
m_out << i; // needs to be as an integer
return *this;
}
// ...and other overloads that do not create an ambiguity issue...
// MyClass & operator<< (const std::string & str)
// MyClass & operator<< (const char * str)
};
void doSomething ()
{
MyClass proc(std::cout);
Stuff s1, s2;
unsigned i = 1;
proc << s1 << "using stuff and strings is fine" << s2;
proc << i; // compile error here: ambiguous overload for 'operator<<' in 'proc << i'
}
Your problem is that the value you're trying to insert is unsigned while the overloads you've provided only work on signed types. As far as the compiler is concerned, converting unsigned to int or char are both equally good/bad and result in ambiguity.
I cannot use a template function because the processing depends on type in some cases
Just make overloadings for those types.
I think the ambiguity would remain between it and those for my specific types (like 'Stuff').
No. If operator<< is overloaded for specific type, this overloading will be called. Otherwise will be called template function.
template <class T>
MyClass& operator<< (const T& t)
{
m_out << t;
return *this;
}
In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is printed.
Here's what I tried to do:
ostream & Score::operator<< (ostream & os, Score right)
{
os << right.getPoints() << " " << right.scoreGetName();
return os;
}
Here are the errors returned:
score.h(30) : error C2804: binary 'operator <<' has too many parameters
(This error appears 4 times, actually)
I managed to get it working by declaring the overload as a friend function:
friend ostream & operator<< (ostream & os, Score right);
And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member).
Why does this work, yet the former piece of code doesn't?
Thanks for your time!
EDIT
I deleted all mentions to the overload on the header file... yet I get the following (and only) error. binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)
How come my test, in main(), can't find the appropriate overload? (it's not the includes, I checked)
Below is the full score.h
#ifndef SCORE_H_
#define SCORE_H_
#include <string>
#include <iostream>
#include <iostream>
using std::string;
using std::ostream;
class Score
{
public:
Score(string name);
Score();
virtual ~Score();
void addPoints(int n);
string scoreGetName() const;
int getPoints() const;
void scoreSetName(string name);
bool operator>(const Score right) const;
private:
string _name;
int _points;
};
#endif
Note: You might want to look at the operator overloading FAQ.
Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// stream obj's data into os
return os;
}
Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either.
Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming
class T {
public:
void stream_to(std::ostream&) const {os << obj.data_;}
private:
int data_;
};
and call that from the operator:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
obj.stream_to(os);
return os;
}
or make the operator a friend
class T {
public:
friend std::ostream& operator<<(std::ostream&, const T&);
private:
int data_;
};
so that it can access the class' private parts:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
os << obj.data_;
return os;
}
Let's say you wanted to write an operator overload for + so you could add two Score objects to each other, and another so you could add an int to a Score, and a third so you could add a Score to an int. The ones where a Score is the first parameter can be member functions of Score. But the one where an int is the first parameter can't become member functions of int, right? To help you with that, you're allowed to write them as free functions. That is what is happening with this << operator, you can't add a member function to ostream so you write a free function. That's what it means when you take away the Score:: part.
Now why does it have to be a friend? It doesn't. You're only calling public methods (getPoints and scoreGetName). You see lots of friend operators because they like to talk directly to the private variables. It's ok by me to do that, because they are written and maintained by the person maintaing the class. Just don't get the friend part muddled up with the member-function-vs-free-function part.
You're getting compilation errors when operator<< is a member function in the example because you're creating an operator<< that takes a Score as the first parameter (the object the method's being called on), and then giving it an extra parameter at the end.
When you're calling a binary operator that's declared as a member function, the left side of the expression is the object the method's being called on. e.g. a + b might works like this:
A a;
B b
a.operator+(b)
It's typically preferable to use non-member binary operators (and in some cases -- e.g. operator<<for ostream is the only way to do it. In that case, a + b might work like this:
A a;
B b
operator+(a, b);
Here's a full example showing both ways of doing it; main() will output '55' three times:
#include <iostream>
struct B
{
B(int b) : value(b) {}
int value;
};
struct A
{
A(int a) : value(a) {}
int value;
int operator+(const B& b)
{
return this->value + b.value;
}
};
int operator+(const A& a, const B& b)
{
return a.value + b.value;
}
int main(int argc, char** argv)
{
A a(22);
B b(33);
std::cout << a + b << std::endl;
std::cout << operator+(a, b) << std::endl;
std::cout << a.operator+(b) << std::endl;
return 0;
}
I am trying to create my own std::string wrapper to extend its functionality.
But I got a problem when declaring the << operator.
Here's my code so far:
my custom string class:
class MyCustomString : private std::string
{
public:
std::string data;
MyCustomString() { data.assign(""); }
MyCustomString(char *value) { data.assign(value); }
void Assign(char *value) { data.assign(value); }
// ...other useful functions
std::string & operator << (const MyCustomString &src) { return this->data; }
};
the main program:
int main()
{
MyCustomString mystring("Hello");
std::cout << mystring; // error C2243: 'type cast' : conversion from 'MyCustomString *' to 'const std::basic_string<_Elem,_Traits,_Ax> &' exists, but is inaccessible
return 0;
}
I wanted cout to treat the class as a std::string, so that I won't need to do something like:
std::cout << mystring.data;
Any kind of help would be appreciated!
Thanks.
Just fyi: my IDE is Microsoft Visual C++ 2008 Express Edition.
If you look at how all stream operators are declared they are of the form:
ostream& operator<<(ostream& out, const someType& val );
Essentially you want your overloaded function to actually do the output operation and then return the new updated stream operator. What I would suggest doing is the following, note that this is a global function, not a member of your class:
ostream& operator<< (ostream& out, const MyCustomString& str )
{
return out << str.data;
}
Note that if your 'data' object was private, which basic OOP says it probably should, you can declare the above operator internally as a 'friend' function. This will allow it to access the private data variable.
You need a free-standing function (friend of your class, if you make your data private as you probably should!)
inline std::ostream & operator<<(std::ostream &o, const MyCustomString&& d)
{
return o << d.data;
}
Firstly, you seem to have an issue with the definition of MyCustomString. It inherits privately from std::string as well as containing an instance of std::string itself. I'd remove one or the other.
Assuming you are implementing a new string class and you want to be able to output it using std::cout, you'll need a cast operator to return the string data which std::cout expects:
operator const char *()
{
return this->data.c_str();
}
That's not how you overload the << operator. You need to pass in a reference to an ostream and return one (so you can stack multiple <<, like std::cout << lol << lol2).
ostream& operator << (ostream& os, const MyCustomString& s);
Then just do this:
ostream& operator << (ostream& os, const MyCustomString& s)
{
return os << s.data;
}