I got an error, when I am trying to overload an operator.
My header file:
#include<iostream>
#include<string>
using namespace std;
#ifndef HALLGATO_H
#define HALLGATO_H
class Hallgato {
private:
char* nev;
char* EHA;
int h_azon;
unsigned int kepesseg;
public:
friend ostream& operator<<(ostream& output, const Hallgato& H);
};
#endif
My cpp file:
#include<iostream>
#include "Hallgato.h"
using namespace std;
ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {
output << "Nev: " << H.nev << " EHA: " << H.EHA << " Azonosito: " << H.h_azon << " Kepesseg: " << H.kepesseg << endl;
return output;
}
};
In my .cpp file, when I want to define the overloaded operator <<, I got an error. Why?
The operator is not a member of the class, it is a friend so
ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {
should be
ostream& operator<<(ostream& output, const Hallgato& H) {
also to be able to use the operator from other files you should add a prototype into the header file.
The header file would become this
hallgato.h
#ifndef HALLGATO_H
#define HALLGATO_H
#include<iostream>
#include<string>
class Hallgato {
private:
char* nev;
char* EHA;
int h_azon;
unsigned int kepesseg;
public:
friend std::ostream& operator<<(std::ostream& output, const Hallgato& H);
};
std::ostream& operator<<(std::ostream& output, const Hallgato& H);
#endif /* End of HALLGATO_H */
Somewhere in a ".cpp" file you would implement the operator function, you can also do it in the header file but then you would have to recompile often with some compilers.
hallgato.cpp
#include "hallgato.h"
std::ostream& operator<<(std::ostream& output, const Hallgato& H)
{
/* Some operator logic here */
}
NOTE:
When you modify header files, many compilers usually do not re-include them in your .cpp files. This is done to avoid unnecessary recompilation. To force a re-include, you have to make some modifications(delete empty line) to the source files which include those headers or force recompilation in your compiler/IDE.
In header file you declared friend method for class
friend ostream& operator<<(ostream& output, const Hallgato& H);
this method shoud be defined (in cpp) without Hallgato::
ostream& operator<<(ostream& output, const Hallgato& H)
because this method is not part of Hallgato class.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have been stuck on what to do with this for loop inside an istream operator, i dont understand why it doesnt find >> operator.
Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'Result' (or there is no acceptable conversion)
any help would be madly appreciated.
#include "pch.h"
#include <iostream>
#include <fstream>
#include "Unit.h"
#include "Registration.h"
istream & operator >>(istream & input, Unit & U);
ostream & operator <<(ostream & os, const Unit & U);
istream & operator >>(istream & input, Result & Re);
ostream & operator <<(ostream & os, const Result & Re);
istream & operator >>(istream & input, Date & D);
ostream & operator <<(ostream & os, const Date & D);
int main()
{
std::cout << "Hello World!\n";
ifstream infile("rinput.txt");
if (!infile)
{
return -1;
}
Registration R;
infile >> R;
ofstream ofile("routput.txt");
ofile << R
<< "Number of units = " << R.getCount() << '\n'
<< "Total credits = " << R.GetCredits() << '\n';
infile.close();
ofile.close();
}
#include "Registration.h"
using namespace std;
Registration::Registration()
{
}
istream & operator >>(istream & input, Registration & R)
{
long idTemp;
unsigned semesterTemp, countTemp;
Registration regTemp;
Result tempResult;
input >> idTemp >> semesterTemp >> countTemp;
regTemp.setStudentId(idTemp);
regTemp.setSemester(semesterTemp);
regTemp.setCount(countTemp);
for (unsigned i = 0; i < R.getCount(); i++)
{
//THIS LINE IS THE ERROR
input >> tempResult;
R.setResult(i, tempResult);
}
return input;
}
//result h file has the following
#ifndef RESULT_H
#define RESULT_H
#include "Date.h"
#include "Unit.h"
class Result
{
public:
Result();
float getMark() const;
void setMark(float mrk);
int GetCredits() const;
const Date & getDate() const;
void setDate(const Date &D);
const Unit & getUnit() const;
void setUnit(const Unit &U);
private:
float mark;
Date dateObject;
Unit unitObject;
};
#endif // !RESULT_H
this is the error:
Severity Code Description Project File Line Suppression State
Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'Result' (or there is no acceptable conversion)
each class that is referenced inside result also has an overloading input stream function.
Here is a simple example
namespace Me {
class A
{
// bla
};
std::ostream& operator<<(std::ostream& os, A& const& obj)
{
// print in terms of public interface of A
// (else, deckare this a friend function inside A)
return os;
}
} // Me
int main()
{
std::cout << A(); // operator<<(ostream&, A const&) is the best match
}
C++ doesn't really have "source" or "header" files, it deals only with translation units.
A translation unit is, in short, a single source file with all included header files. Most importantly, a translation unit is its own independent unit, without any knowledge of other translation units.
That means declarations put in one translation unit (source file) will now be known by a different translation unit.
For a declaration to be known to all translation units that are linked into the final executable program, you should put them in a header file that is included everywhere needed.
Example:
Header file result.h:
#ifndef RESULT_H
#define RESULT_H
class Result
{
// ...
};
std::istream & operator >>(std::istream & input, Result & C);
std::ostream & operator <<(std::ostream & os, const Result & C);
#endif
"Main" source file main.cpp:
#include <iostream>
#include "result.h" // "Import" the `operator>>` declaration
int main()
{
Result result;
std::cin >> result;
}
"Result" class implementation source file result.cpp
#include <iostream>
#include "result.h"
// Result class implementation...
std::istream & operator >>(std::istream & input, Result & C)
{
// Read input...
return input;
}
When building the above example, you build the two source files separately as two separate translation units. The result of each translation unit is an object file. Then you link those two object files into the executable file.
Just got into C++ and I have a quick question.
After compiling with
g++ *.cpp -o output
I receive this error:
error: 'ostream' in 'class Dollar' does not name a type
These are my three files:
main.cpp
#include <iostream>
#include "Currency.h"
#include "Dollar.h"
using namespace std;
int main(void) {
Currency *cp = new Dollar;
// I want this to print "printed in Dollar in overloaded << operator"
cout << cp;
return 0;
}
Dollar.cpp
#include <iostream>
#include "Dollar.h"
using namespace std;
void Dollar::show() {
cout << "printed in Dollar";
}
ostream & operator << (ostream &out, const Dollar &d) {
out << "printed in Dollar in overloaded << operator";
}
Dollar.h
#include "Currency.h"
#ifndef DOLLAR_H
#define DOLLAR_H
class Dollar: public Currency {
public:
void show();
};
ostream & operator << (ostream &out, const Dollar &d);
#endif
Thank you for your time, and everything helps!
You have a number of errors in the code.
You heavily use using namespace std. This is a bad practice. In particular, this led to the error you faced: you don't have using namespace std in Dollar.h, thus the compiler has no idea what ostream means. Either put using namespace std in Dollar.h too, or better just stop using it and specify the std namespace directly, as in std::ostream.
You use std::ostream in your headers, but you don't include the corresponding standard library header <ostream> in them (<ostream> contains the definition of std::ostream class; for the full I/O library include <iostream>). A really good practice is to include all the dependencies of the header in the header itself, so that it is self-contained and can be safely included anywhere.
You are implementing a stream output operator with signature std::ostream & operator << (std::ostream &, Dollar const &), which is perfectly valid. However, you call it for a pointer to type Dollar. You should rather call it with the object itself, not the pointer, so you should dereference the pointer: std::cout << *cp;.
You implemented the output operator for the Dollar class, but use it for a variable of type Currency: this won't work. There is a way to do this - there do exist virtual methods for this exact reason. However, in this case the operator is a free function, thus it cannot be virtual. So, you should probably add a virtual print method to your Currency class, implement it in Dollar, and call it from output operator:
#include <iostream>
class Currency {
public:
virtual void print (std::ostream &) const = 0;
};
class Dollar : public Currency {
void print (std::ostream & out) const override {
out << "A dollar";
}
};
std::ostream & operator << (std::ostream & out, Currency const & c) {
c.print(out);
return out;
}
int main(/* void is redundant here */) {
Currency *cp = new Dollar;
std::cout << *cp;
// return 0 is redundant in main
}
You need to #include <iostream> within Dollar.h so that your std::ostream & operator is resolved by the compiler.
I get this when i try to compile:
../Monster.h:26:9: error: ‘int ProjectIV::Monster::con’ is private
`int con;`
^
../Monster.cpp:17:39: error: within this context
cout << "Constitution: " << monster.con << endl;
^
make: * [Monster.o] Error 1
From what I understand making operator<< a friend should allow it to access int con. What am I not seeing.
Monster.h:
#ifndef MONSTER_H_
#define MONSTER_H_
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
#include <string>
using std::string;
namespace ProjectIV
{
class Monster
{
friend ostream &operator<< (ostream &out, const Monster &monster);
public:
Monster(int con);
private:
int con;
};
} /* namespace ProjectIV */
#endif /* MONSTER_H_ */
Monster.cpp:
#include "Monster.h"
ostream &operator<< (ostream &out, const ProjectIV::Monster &monster)
{
cout << "Constitution: " << monster.con << endl;
return out;
}
ProjectIV::Monster::Monster(int con): con(con)
{}
main.cpp:
#include "Monster.h"
using namespace ProjectIV;
int main()
{
Monster Gojira(140);
cout << Gojira << endl;
return 0;
}
This:
ostream& operator<<(ostream& out, const ProjectIV::Monster& monster)
should be:
ostream& ProjectIV::operator<<(ostream& out, const ProjectIV::Monster& monster)
Here your not working example, and here is the working one.
Also, as per AndreyT's comment, you should add a function declaration before the friend declaration:
namespace ProjectIV {
class Monster {
friend ostream& operator<<(ostream& out, const Monster& monster);
public:
Monster(int con);
private:
int con;
};
ostream& operator<<(ostream& out, const Monster& monster);
// ^^^ this
}
There are two problems with your code.
Firstly, the friend declaration inside Monster class refers to ProjectIV::operator << function. It is ProjectIV::operator << that will become the friend of Monster. What you defined in your Monster.cpp file is actually a ::operator <<. This is a completely different function that is not a friend of Monster. This is why you get the error.
So, you need to decide what function you want to make a friend - the one in global namespace or the one in ProjectIV namespace - and act accordingly.
If you want to make your operator << a member of ProjectIV namespace, you run into the second problem. Friend declarations refer to member of enclosing namespace, but they don't introduce the corresponding declarations into the enclosing namespace. It is still your responsibility to add a declaration for operator << in ProjectIV
namespace ProjectIV
{
class Monster
{
friend ostream &operator<< (ostream &out, const Monster &monster);
public:
Monster(int con);
private:
int con;
};
ostream &operator<< (ostream &out, const Monster &monster);
} /* namespace ProjectIV */
and then later define it as a member of ProjectIV
ostream &ProjectIV::operator<< (ostream &out, const ProjectIV::Monster &monster)
{
cout << "Constitution: " << monster.con << endl;
return out;
}
I am attempting to override the << operator for a class. The purpose is basically to implement a toString() like behavior for my class, so that sending it to cout will produce useful output. Using a dummy example, I have the code below. When I attempt to compile, I get the foollowing error:
$ g++ main.cpp Rectangle.cpp
/tmp/ccWs2n6V.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)':
Rectangle.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)'
/tmp/ccLU2LLE.o:main.cpp:(.text+0x0): first defined here
I can't figure out why this is happening. my code is below:
Rectangle.h:
#include <iostream>
using namespace std;
class CRectangle {
private:
int x, y;
friend ostream& operator<<(ostream& out, const CRectangle& r);
public:
void set_values (int,int);
int area ();
};
ostream& operator<<(ostream& out, const CRectangle& r){
return out << "Rectangle: " << r.x << ", " << r.y;
}
Rectangle.cpp:
#include "Rectangle.h"
using namespace std;
int CRectangle::area (){
return x*y;
}
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
main.cpp:
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main () {
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
You're breaking the one definition rule. A quick-fix is:
inline ostream& operator<<(ostream& out, const CRectangle& r){
return out << "Rectangle: " << r.x << ", " << r.y;
}
Others are:
declaring the operator in the header file and moving the implementation to Rectangle.cpp file.
define the operator inside the class definition.
.
class CRectangle {
private:
int x, y;
public:
void set_values (int,int);
int area ();
friend ostream& operator<<(ostream& out, const CRectangle& r){
return out << "Rectangle: " << r.x << ", " << r.y;
}
};
Bonus:
use include guards
remove the using namespace std; from the header.
You are putting the definition of a function in a .h file, which means that it will appear in every translation unit, violating the One Definition Rule (=> you defined operator<< in every object module, so the linker doesn't know which is "the right one").
You can either:
write just the declaration of your operator (i.e. its prototype) in the .h file and move its definition to rectangle.cpp
make operator<< inline - inline functions are allowed to be defined more than once, as long as all the definitions are identical.
(Also, you should use header guards in your includes.)
I'm having an issue with my operator<< overloading where I can not access the private variables of the class it is in no matter what I do because it will say that the variables are private as a compiler error. This is my current code:
#include "library.h"
#include "Book.h"
using namespace cs52;
Library::Library(){
myNumberOfBooksSeenSoFar=0;
}
//skipping most of the functions here for space
Library operator << ( ostream &out, const Library & l ){
int i=myNumberOfBooksSeenSoFar;
while(i<=0)
{
cout<< "Book ";
cout<<i;
cout<< "in library is:";
cout<< l.myBooks[i].getTitle();
cout<< ", ";
cout<< l.myBooks[i].getAuthor();
}
return (out);
}
And the function prototype and private variables in library.h are
#ifndef LIBRARY_H
#define LIBRARY_H
#define BookNotFound 1
#include "Book.h"
#include <iostream>
#include <cstdlib>
using namespace std;
namespace cs52{
class Library{
public:
Library();
void newBook( string title, string author );
void checkout( string title, string author ) {throw (BookNotFound);}
void returnBook( string title, string author ) {throw (BookNotFound);}
friend Library operator << ( Library& out, const Library & l );
private:
Book myBooks[ 20 ];
int myNumberOfBooksSeenSoFar;
};
}
#endif
Your << operator should have this protoype:
std::ostream& operator << ( std::ostream &out, const Library & l )
^^^^^^^^^^^^^
You need to return a reference to std::ostream object so that you can chain stream operations.
Also, If you declare it as friend in your Library class you should be able to access all the members(private/protected) of the Library class in your overloaded function.
As such i fail to understand your code, You declared your << operator as:
friend Library operator << ( Library& out, const Library & l );
^^^^^^^^^^^^
You defined your operator function with prototype:
Library operator << ( ostream &out, const Library & l )
^^^^^^^^^^^
They are different!
In short you never declared the function where you are accessing the private member as a friend of your class and Hence the error.
Also, the return type is Incorrect as I mentioned before.