I was practicing some c++ (trying to leave Java), and I stumbled on this annoying error saying:Error: No operater << matches these operands. I've searched this website for a clear answer and no luck, I did find that I'm not the only one.
This error is in my .cpp file, there are other errors, but I'm not paying any mind to them right now.
void NamedStorm::displayOutput(NamedStorm storm[]){
for(int i = 0; i < sizeof(storm); i++){
cout << storm[i] << "\n";
}
}
Something is up with the "<<" im not sure whats going on.
Since you are trying cout a class object you need to overload <<
std::ostream& operator<<(ostream& out, const NamedStorm& namedStorm)
You must overload the << operator in order to redirect your object into a stream.
You can overload as a member function, but in this case you must use the syntax object << stream in order to use that overloaded function.
If you wish to use this syntax stream << object then you must overload the << operator as a 'free' function, that is, not a member of your NamedStorm class.
Here is a working example:
#include <string>
#include <iostream>
class NamedStorm
{
public:
NamedStorm(std::string name)
{
this->name = name;
}
std::ostream& operator<< (std::ostream& out) const
{
// note the stream << object syntax here
return out << name;
}
private:
std::string name;
};
std::ostream& operator<< (std::ostream& out, const NamedStorm& ns)
{
// note the (backwards feeling) object << stream syntax here
return ns << out;
}
int main(void)
{
NamedStorm ns("storm Alpha");
// redirect the object to the stream using expected/natural syntax
std::cout << ns << std::endl;
// you can also redirect using the << method of NamedStorm directly
ns << std::cout << std::endl;
return 0;
}
The function which is called from the free redirection overload must be a public method of NamedStorm (in this case we are calling the operator<< method of the NamedStorm class), OR the redirection overload must be a friend of the NamedStorm class in order to access private fields.
Related
I'm switching from C to C++ and i have some basic but annoying problem with Class hermetization. I did some research here, but I'm probably really dumb and I can't use yor methods properly, could you help me?
The problem is printing private member of a class via overloaded '<<' operator.
Let's get to the code:
In file Vector.hh
#include <iostream>
class Vector {
double Val1, Val2, Val3;
public:
void PrintVector(Vector);
//There is also a constructor but it doesn't really matter
}
In File Vector.cpp
#include "Vector.hh"
#include <iostream>
void Vector::PrintVector(Vector Wek)
{
std::cout << Wek.Val1 << Wek.Val2 << Wek.Val3 << std::endl;
}
std::istream& operator >> (std::istream &Strm, Vector &Wek)
{
//It actually works with no problem so i'll pass it
}
std::ostream& operator << (std::ostream &Strm, Vector Wek)
{
Vector::PrintVector(Wek);
return Strm;
}
and in main.cpp
#include Vector.hh
#include <iostream>
using namespace std;
int main()
{
Vector Vector1;
cout << endl << " Start " << endl << endl;
cin >> Vector1;
cout << Vector1;
}
When I try to compile g++ says:
g++ -c -g -Iinc -Wall -pedantic -o obj/Vector.o src/Vector.cpp
src/Vector.cpp:12:37: error: no 'void Vector::PrintVector(Vector)' member function declared in class 'Vector'
void Vector::PrintVector(Vector Wek)
^
src/Vector.cpp: In function 'std::ostream& operator<<(std::ostream&, Vector)':
src/Vector.cpp:29:1: error: 'PrintVector' is not a member of 'Vector'
Vector::PrintVector(Wek);
make: Fatal error: Command failed for target `obj/Vector.o'
Could you please give me a hand with it so I learn basics properly?
Either a class function is static and not called on any particular class object, or it is non-static and must be called on an instance of the class, which can be used inside the function. You have mixed the approach. You need to select one of the two:
class Vector
{
static void PrintVector(const Vector& Wek)
{
std::cout << Wek.Val1 << Wek.Val2 << Wek.Val3 << std::endl;
}
};
// to call
Vector::PrintVector(Wek);
or
class Vector
{
void PrintVector() const
{
std::cout << Wek.Val1 << Wek.Val2 << Wek.Val3 << std::endl;
}
};
// to call
Wek.PrintVector();
Either is fine, but I would prefer the latter.
The other problem is how you have implemented the stream operator. This operator takes a stream to output the object to. You have called this stream Strm, but it is never used in your operator. Your print function is hardcoded to the cout stream.
I suggest you remove the PrintVector function and implement your operator as follows:
class Vector
{
friend std::ostream& operator << (std::ostream &Strm, const Vector& Wek);
};
std::ostream& operator << (std::ostream &Strm, const Vector& Wek)
{
Strm << Wek.Val1 << Wek.Val2 << Wek.Val3 << "\n";
return Strm;
}
Now you can output to any type of stream, such as a file stream. You also needed to declare the operator as a friend to allow it to access the private members.
I changed some parameters to reference to increase speed and also replaced endl with "\n" which is faster when writing to files (you can google why).
You may want to consider adding spaces between the output members, as this makes it easer to read back.
Hope this helps.
Your error is simple. You cannot use an instance method without an object. Try:
Wek.PrintVector();
Also, pass it by constant reference, don't copy.
General way to do this is to make operator<<() a friend function of the class. Friend function can access private members of the class. So operator<<() can directly access private members for printing them. Refer sample.
Defining a public function PrintVector for printing is a bad idea. Since it is public, user (developer using your class) might start using it instead of << operator. You don't want user to use it.
Is it possible to write a method that takes a stringstream and have it look something like this,
void method(string str)
void printStringStream( StringStream& ss)
{
method(ss.str());
}
And can be called like this
stringstream var;
printStringStream( var << "Text" << intVar << "More text"<<floatvar);
I looked up the << operator and it looks like it returns a ostream& object but I'm probably reading this wrong or just not implementing it right.
Really all I want is a clean way to concatenate stuff together as a string and pass it to a function. The cleanest thing I could find was a stringstream object but that still leaves much to be desired.
Notes:
I can't use much of c++11 answers because I'm running on Visual Studio 2010 (against my will, but still)
I have access to Boost so go nuts with that.
I wouldn't be against a custom method as long as it cleans up this mess.
Edit:
With #Mooing Duck's answer mixed with #PiotrNycz syntax I achieved my goal of written code like this,
try{
//code
}catch(exception e)
{
printStringStream( stringstream() << "An exception has occurred.\n"
<<" Error: " << e.message
<<"\n If this persists please contact "<< contactInfo
<<"\n Sorry for the inconvenience");
}
This is as clean and readable as I could have hoped for.
Hopefully this helps others clean up writing messages.
Ah, took me a minute. Since operator<< is a free function overloaded for all ostream types, it doesn't return a std::stringstream, it returns a std::ostream like you say.
void printStringStream(std::ostream& ss)
Now clearly, general ostreams don't have a .str() member, but they do have a magic way to copy one entire stream to another:
std::cout << ss.rdbuf();
Here's a link to the full code showing that it compiles and runs fine http://ideone.com/DgL5V
EDIT
If you really need a string in the function, I can think of a few solutions:
First, do the streaming seperately:
stringstream var;
var << "Text" << intVar << "More text"<<floatvar;
printStringStream(var);
Second: copy the stream to a string (possible performance issue)
void printStringStream( ostream& t)
{
std::stringstream ss;
ss << t.rdbuf();
method(ss.str());
}
Third: make the other function take a stream too
Make your wrapper over std::stringstream. In this new class you can define whatever operator << you need:
class SSB {
public:
operator std::stringstream& () { return ss; }
template <class T>
SSB& operator << (const T& v) { ss << v; return *this; }
template <class T>
SSB& operator << (const T* v) { ss << v; return *this; }
SSB& operator << (std::ostream& (*v)(std::ostream&)) { ss << v; return *this; }
// Be aware - I am not sure I cover all <<'s
private:
std::stringstream ss;
};
void print(std::stringstream& ss)
{
std::cout << ss.str() << std::endl;
}
int main() {
SSB ssb;
print (ssb << "Hello" << " world in " << 2012 << std::endl);
print (SSB() << "Hello" << " world in " << 2012 << std::endl);
}
For ease of writing objects that can be inserted into a stream, all these classes overload operator<< on ostream&. (Operator overloading can be used by subclasses, if no closer match exists.) These operator<< overloads all return ostream&.
What you can do is make the function take an ostream& and dynamic_cast<> it to stringstream&. If the wrong type is passed in, bad_cast is thrown.
void printStringStream(ostream& os) {
stringstream &ss = dynamic_cast<stringstream&>(os);
cout << ss.str();
}
Note: static_cast<> can be used, it will be faster, but not so bug proof in the case you passed something that is not a stringstream.
Since you know you've got a stringstream, just cast the return value:
stringstream var;
printStringStream(static_cast<stringstream&>(var << whatever));
Just to add to the mix: Personally, I would create a stream which calls whatever function I need to call upon destruction:
#include <sstream>
#include <iostream>
void someFunction(std::string const& value)
{
std::cout << "someFunction(" << value << ")\n";
}
void method(std::string const& value)
{
std::cout << "method(" << value << ")\n";
}
class FunctionStream
: private virtual std::stringbuf
, public std::ostream
{
public:
FunctionStream()
: std::ostream(this)
, d_function(&method)
{
}
FunctionStream(void (*function)(std::string const&))
: std::ostream(this)
, d_function(function)
{
}
~FunctionStream()
{
this->d_function(this->str());
}
private:
void (*d_function)(std::string const&);
};
int main(int ac, char* av[])
{
FunctionStream() << "Hello, world: " << ac;
FunctionStream(&someFunction) << "Goodbye, world: " << ac;
}
It is worth noting that the first object sent to the temporary has to be of a specific set of types, namely one of those, the class std::ostream knows about: Normally, the shift operator takes an std::ostream& as first argument but a temporary cannot be bound to this type. However, there are a number of member operators which, being a member, don't need to bind to a reference! If you want to use a user defined type first, you need to extract a reference temporary which can be done by using one of the member input operators.
I wrote this simple program to practice overloading.
This is my code:
#include <iostream>
#include <string>
using namespace std;
class sex_t
{
private:
char __sex__;
public:
sex_t(char sex_v = 'M'):__sex__(sex_v)
{
if (sex_v != 'M' && sex_v != 'F')
{
cerr << "Sex type error!" << sex_v << endl;
__sex__ = 'M';
}
}
const ostream& operator << (const ostream& stream)
{
if (__sex__ == 'M')
cout << "Male";
else
cout << "Female";
return stream;
}
};
int main(int argc, char *argv[])
{
sex_t me('M');
cout << me << endl;
return 0;
}
When I compile it, it print lots of error messages:
The error message was in a mess.
It's too hard for me to found a useful message.
sex.cpp: 在函数‘int main(int, char**)’中:
sex.cpp:32:10: 错误: ‘operator<<’在‘std::cout << me’中没有匹配
sex.cpp:32:10: 附注: 备选是:
/usr/include/c++/4.6/ostream:110:7: 附注: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostre
The argument and return from operator<< are non-const. Also it needs to be a non-member- you have written an overload for me << cout, not cout << me. Also, identifiers leading with two underscores are reserved for the implementation and using them is Undefined Behaviour.
"C++ Primer 4th Edition" Chapter 14 section 14.2 Input and Output Operators:
IO Operators Must Be Nonmember Functions, We cannot make the operator a member of our own class. If we did, then the left-hand operand would have to be an object of our class type:
// if operator<< is a member of Sales_item
Sales_item item;
item << cout;
The general skeleton of an overloaded output operator is
// general skeleton of the overloaded output operator
ostream&
operator <<(ostream& os, const ClassType &object)
{
// any special logic to prepare object
// actual output of members
os << // ...
// return ostream object
return os;
}
The first parameter is a reference to an ostream object on which the output will be generated. The ostream is nonconst because writing to the stream changes its state. The parameter is a reference because we cannot copy an ostream object.
The second parameter ordinarily should be a const reference to the class type we want to print. The parameter is a reference to avoid copying the argument. It can be const because (ordinarily) printing an object should not change it. By making the parameter a const reference, we can use a single definition to print const and nonconst objects.
The return type is an ostream reference. Its value is usually the ostream object against which the output operator is applied.
EDIT:
I tried to modify your code, and if you use __sex__ as sex_t's private member, you should write another get function to get the 'M' or 'F', and if you call it in your operator<< function, you will probably get an error, because a const reference could only call a const function, so you should make your get function a const function, just for reminde:)
When overloading for streams, you declare a << operator globally and/or as a friend (with benefits) to your class so it can access its 'private members' (ooh...). You can declare a friend inside the class to declare it globally. Do not use const on the streams.
Next, use the passed stream in your overload. In your method, you use cout when you would have used it anyway by just using the stream argument.
I have not tested this, but see if it works for you.
class sex_t
{
private:
char __sex__;
public:
sex_t(char sex_v = 'M'):__sex__(sex_v)
{
if (sex_v != 'M' && sex_v != 'F')
{
cerr << "Sex type error!" << sex_v << endl;
__sex__ = 'M';
}
}
friend ostream& operator << (ostream& stream, sex_t& sex);
};
ostream& operator << (ostream& stream, sex_t& sex)
{
if (__sex__ == 'M')
stream << "Male";
else
stream << "Female";
return stream;
}
I've come across functions that, rather than overloading the operator << to use with cout, declare a function that takes an ostream and returns an ostream
Example:
#include <iostream>
class A {
private:
int number;
public:
A(int n) : number(n) {}
~A() {}
std::ostream& print(std::ostream& os) const;
friend std::ostream& operator<<(std::ostream& os, const A a);
};
An example of implementation:
std::ostream& A::print(std::ostream& os) const {
os << "number " << number;
return os;
}
std::ostream& operator<<(std::ostream& os, const A a) {
os << "number " << a.number;
return os;
}
Now if I run this I can use the different functions in different situations.. E.g.
int main() {
A a(1);
std::cout << "Object."; a.print(std::cout);
std::cout << "\n\n";
std::cout << "Object." << a;
std::cout << "\n\n";
return 0;
}
Output:
Object.number 1
Object.number 1
There doesn't seem to be a situation where the print function would be needed since you could only use separately or in the beginning of a "cout chain" but never in the middle or end of it which perhaps makes it useless. Wouldn't it (if no other use is found) be better off using a function "void print()" instead?
It would make sense where an inheritance hierarchy comes in to play. You can make the print method virtual, and in the operator for the base class, delegate to the virtual method to print.
It would make a lot more sense if operator<<() actually looked like
std::ostream& operator<<(std::ostream& os, const A a) {
return a.print(os);
}
Then operator<<() wouldn't need to be a friend.
A function that can be used as the start of a cout chain certainly sounds more useful than one that can't, all other things being equal.
I've implemented several functions with signatures like you describe because operator<< is only one name, and sometimes I need to have objects streamed in multiple different ways. I have one format for printing to the screen, and another format for saving to a file. Using << for both would be non-trivial, but choosing a human-readable name for at least one of the operations is easy.
The use of operator<< assumes that there is only one sensible way to print data. And sometimes that is true. But sometimes there are multiple valid ways to want to output data:
#include <iostream>
using std::cout; using std::endl;
int main()
{
const char* strPtr = "what's my address?";
const void* address = strPtr;
// When you stream a pointer, you get the address:
cout << "Address: " << address << endl;
// Except when you don't:
cout << "Not the address: " << strPtr << endl;
}
http://codepad.org/ip3OqvYq
In this case, you can either chose one of the ways as the way, and have other functions (print?) for the rest. Or you can just use print for all of them. (Or you might use stream flags to trigger which behavior you want, but that's harder to set up and use consistently.)
class object_1
{
public:
...
friend ofstream& operator<<(ofstream &out, const object_1 &obj_1);
friend object_2;
private:
char *pCh_mem1;
char *pCh_mem2;
int *pInt_mem1;
int *pInt_mem2;
};
class object_2
{
public:
...
friend ofstream& operator<<(ofstream &out, const object_2 &obj_2);
friend object_1;
};
Object1's implementation file is typical. Ctor, Dtor and some methods. I havent posted the method declarations in the header because their irrelevant to my problem.
It is very important that I discuss the objects lifetime.It is something that I really need to understand. Whats happening is that the operator overload function is then invoked when I call object_2 in main. So then the operator overload function is called:
ostream& operator<<(ostream& out, const object_2& obj_2)
{
object1::display(out) //Calls method display in object1's I.F.
return out;
}
here we are:
void object_1::display(std::ostream &out)
{
out << left << setw(28) << "Person" << setw(20) << "Place" ;
out << right << setw(5) << "Thing" << setw(5) << "Idea" << endl;
out << left << setw(28) << "----" << setw(20) << "--------" ;
out << right << setw(5) << "----- " << setw(5) << "------" << endl;
}
At the top of the implementation file is the IOMANIP library. So setw(X) and everything are defined. Im getting 0's all prinited to the console. Did my object go out of scope? I think so because when i do all these before I need to, it works fine. That is, when I call this function n e where else than in the body of the operator overload it works. I think because the object is redeclared:
ostream& operator<<(ostream& out, const object_2& obj_2);
then after I print the formatting method I need to print the information that was passed in from main to the first object's ctor; object_1. When that happens we are in the overload function which is similar and its the same implementation file. Im calling both methods from the overload in the second objects overload function:
ostream& operator<<(ostream& out, const object_1& obj_1)
{
out << obj_1.pCh_mem1 << obj_1.pCh_mem2;
return out;
}
// main
object_2 obj_2(4);
static void method1()
{
//do stuff
}
static void method2()
{
//do stuff
}
static void method3()
{
//do stuff
}
int main(void)
{
method1();
method2();
method3();
cout << obj_2;
return 0; // and such
}
Once objc_2 is called like u see above, the operator overload for object2's class will then be called. I cant use any of my private members because its an illegal operatation. I guess my questions is. How can i print my private members from object1 in my object2's operator overloading function? static_cast's? I have a random snippet from main, Its complicated and I cant alter it.
ostream& operator<<(ostream& out, const object_2& obj_2)
{
object1::display(out) //Calls method display in object1's I.F.
return out;
}
What i've been trying to do, like you see above is call the other objects methods, and get the info from their. But that info is all NULL!! Im hopping from one I.F. to the next and its all NULL!!
AFAICT, object_1 and object_2 are unrelated classes (except that they are friends). So an object_2 does not have any state relevant to an object_1.
Therefore, when you try to print an object_2 as if it were an object_1, this cannot possibly work. It is surprising that this call works at all:
ostream& operator<<(ostream& out, const object_2& obj_2)
{
object1::display(out) //Calls method display in object1's I.F.
return out;
}
since there is no object_1 around here for which a method can be called (but then, you probably didn't mean this to be real code, since it's missing a semicolon also).
It's not completely clear what you want to achieve. Maybe you want object_2 to inherit from object_1, so that any object_2 will also have the members pCh_mem1 etc? Maybe you want a member of object_2 to be an object of type object_1?
ostream& operator<<(ostream& out, const object_2& obj_2)
{
out << object_1[thatIndexThatIstoreditAt]
return out;
}
I need to write a few reports on this stuff. =)