error: declaration of 'operator<<' as non-function| - c++

I am having a really hard time with overloading the << operator. I am working on a homework assignment where I can only modify certain portions of the code. Before you ask, I AM stuck using a struct instead of a class. Here are the portions of the affected code:
The calling function is:
/*
* Write a CSV report listing each course and its enrollment.
*/
void generateReport (ostream& reportFile,
int numCourses,
Course* courses)
{
for (int i = 0; i < numCourses; ++i)
{
//courses is an array of "Course" structs
reportFile << courses[i] << endl;
}
}
Here is the .h file:
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <string>
struct Course {
std::string name;
int maxEnrollment;
int enrollment;
Course();
Course(std::string cName);
std::ostream& operator << (ostream &out, const Course &c);
};
#endif
Here is the .cpp file:
#include "course.h"
using namespace std;
Course::Course()
{
name = "";
maxEnrollment = 0;
enrollment = 0;
}
Course::Course(string cName)
{
name = cName;
maxEnrollment = 0;
enrollment = 0;
}
// send course to file
ostream& Course::operator << (ostream &out, const Course &c)
{
out << c.name << "," << c.enrollment << endl;
return out;
}
Here is the error message I keep getting:
error: declaration of 'operator<<' as non-function|
I have been searching the internet for hours and tried lots of different approaches to solve this problem with no success.
Please help!!
I tried a couple of different methods to fix this based on advice. Here are two methods I tried which did not work:
Method 1:
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <string>
struct Course {
std::string name;
int maxEnrollment;
int enrollment;
Course();
Course(std::string cName);
};
//Moved this outside the struct
std::ostream& operator << (ostream &out, const Course &c);
#endif
Method 2 (also failed to change error):
#include "course.h"
using namespace std;
Course::Course()
{
name = "";
maxEnrollment = 0;
enrollment = 0;
}
Course::Course(string cName)
{
name = cName;
maxEnrollment = 0;
enrollment = 0;
}
std::ostream& operator << (ostream &out, const Course &c);
// send course to file
ostream& Course::operator << (ostream &out, const Course &c)
{
out << c.name << "," << c.enrollment << endl;
return out;
}
RE-EDIT--------------------------------------------------------
After some of the comments and help, here is my current code:
In the .h file:
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <string>
struct Course {
std::string name;
int maxEnrollment;
int enrollment;
Course();
Course(std::string cName);
std::ostream& operator << (std::ostream &out, const Course &c);
};
#endif
In the .cpp file:
#include "course.h"
using namespace std;
Course::Course()
{
name = "";
maxEnrollment = 0;
enrollment = 0;
}
Course::Course(string cName)
{
name = cName;
maxEnrollment = 0;
enrollment = 0;
}
// send course to file
ostream& operator << (ostream &out, const Course &c)
{
out << c.name << "," << c.enrollment << endl;
return out;
}

You forgot to include <ostream> and the namespace specifier std:: in your argument, which leads into your error.
Read on if you want to hear about your next error:
std::ostream& operator << (std::ostream &out, const Course &c);
This means that you define an operator which should work on a current instance of a Course as left hand side (*this), since it is defined as a member. This would lead into an operator that has one left hand side and two right hand sides, which isn't possible.
You need to define the operator as a non-member function, since the left hand side should be an ostream& and not Course&.

std::ostream& operator << (std::ostream &out, const Course &c);
should be
friend std::ostream& operator << (std::ostream &out, const Course &c);
And
std::ostream& Course::operator << (std::ostream &out, const Course &c) // Not a member of Course
{
should be
std::ostream& operator << (std::ostream &out, const Course &c)
{
Since it is not a member of Course.

std::ostream& operator << (ostream &out, const Course &c); inside the Course declaration, must be declared as friend, otherwise it cannot take two parameters.
also, the fist parameter must be std::ostream& and not just ostream&

Related

error: 'VD<Class1> Class2::data' is private within this context

I'm having some problems with my code. I declared in the .h two friend functions which are:
#ifndef CLASS2_H
#define CLASS2_H
#include "class1.h"
#include <string>
#include <iostream>
using namespace std;
class Class2{
private:
VD<Class1> data; //Vector of objects of Class1
VD<int> number; //Vector of int
public:
Constructor();
friend istream & operator >> (istream & i, const Class1 & other);
friend ostream & operator << (ostream &o, const Class1 & other);
};
#endif
And the .cpp is:
istream & operator >> (istream & i,Class2 & other){
string n;
Class1 ing;
getline(i,n);
while(!i.eof()){
i >> ing;
otro.data.Insert(ing,otro.data.size()-1);
}
return i;
}
ostream & operator << (ostream &o, const Ingredientes & otro){
for(int i = 0; i < otro.datos.size(); i++){
o << other.data[i];
}
return o;
}
So, the error that I'm getting is:
error: 'VD Class2::data' is private within this context. I declared the functions of operator >> y << friend but I doesn't make any sense that compiler says to me that I can't access to the private data. Any help please?
You seem to be very new at C++, and you seem to be doing quite complex things, while you're not understanding the basics yet. Please find a tutorial or so.
A few things:
using namespace std; is -especially in a header- never a good idea. It's like you're going on holiday, but bring along everything in your house. Refer to standard namespace functions using std::.
an istream& operator>>() cannot put anything in an object that is declared const.
using vec.insert(obj, vec.size()-1) is reinventing one of the most essential funcitons of std::vector: push_back()...
while (!i.eof()) is not good, because eof is not set until after the read past the end.
there's no string& operator>>(string& str, Class1& obj) function defined. We have std::stringstream for that.
To show how you could realize some of this, I'm going to write some example code. Please don't just copy it, but try to understand it.
test.txt
1 2 3 4
5 6 7 8
main.cpp
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
template <typename T>
using VD = std::vector<T>;
class Class1 {
private:
int d;
public:
friend std::istream& operator>> (std::istream& i, Class1& obj) {
i >> obj.d;
return i;
}
friend std::ostream& operator<< (std::ostream& o, const Class1& obj) {
o << obj.d;
return o;
}
};
class Class2 {
private:
VD<Class1> data{}; //Vector of objects of Class1
public:
void Clear() { data.clear(); }
friend std::istream& operator>> (std::istream& i, Class2& obj) {
std::string line;
std::getline(i, line);
std::istringstream iss(line);
Class1 ing;
while (iss >> ing) {
obj.data.push_back(ing);
}
return i;
}
friend std::ostream& operator<< (std::ostream& o, const Class2& obj) {
for (auto const& cl1 : obj.data) {
o << cl1 << " ";
}
return o;
}
};
int main() {
Class2 cl2;
std::ifstream ifs;
ifs.open("test.txt");
if (ifs.is_open()) {
ifs >> cl2;
}
std::cout << "first line: " << cl2 << '\n';
cl2.Clear();
if (ifs.is_open()) {
ifs >> cl2;
}
std::cout << "second line: " << cl2 << '\n';
ifs.close();
}

Friend ostream can't access private member

I have seen other questions like this but I didn't get a solution.
Here is the codeļ¼š
cout_overload.h:
#ifndef COUT_OVERLOAD_H_
#define COUT_OVERLOAD_H_
#include <iostream>
class A
{
private:
int data;
public:
A(int d);
friend std::ostream & operator <<
(std::ostream os, const A &t );
};
#endif
cout_overload_r.cpp:
#include <iostream>
#include "cout_overload.h"
A::A(int d)
{
data = d;
}
std::ostream &operator << (std::ostream &os, const A&t)
{
os << " t = " << t.data ;
return os;
}
main.cpp:
#include <iostream> #include "cout_overload.h"
int main(void)
{
A ra(1);
using std::cout;
// cout<<ra;
return 0;
}
the error during compiling:
You need to modify your friend function and Use ostream& inside the
friend std::ostream & operator << (std::ostream os, const A &t );
And replace your above line,
friend std::ostream & operator << (std::ostream &os, const A &t );
Because ostream is an output stream, the & is to pass by reference ( the only way to pass streams to functions )..

ostream& does not name a type error. What am I doing wrong here?

I am a learner. I am working on operator overloading. I am trying to write a code for overloading [] and print the elements in the member array. But when I am overloading << to print the member array, I get the error, ostream& does not have a type. What am I doing wrong here? Also what can I do if I have a class that has two member arrays? Here is my code below:
#include <iostream>
#include <cassert>
class Digit
{
private:
int digit1[3]{0};
public:
int& operator[](const int index);
ostream& operator<<(ostream& out);
};
int& Digit::operator[](const int index)
{
return digit1[index];
}
ostream& Digit::operator<<(ostream& out)
{
int loop;
out << "{";
for (loop = 0; loop < 10; loop++)
{
out << digit1[loop] << " ";
}
out << "}";
return o;
}
int main()
{
using namespace std;
Digit n;
n[0] = 4;
n[1] = 3;
n[2] = 4;
n << cout;
return 0;
}
You have put
int main()
{
using namespace std;
//....
This cannot be seen where you declare your << operator. One solution is to change the signature to include the namesape:
In the class:
std::ostream& operator<<(std::ostream& out)
and then
std::ostream& Digit::operator<<(std::ostream& out)
While you are there, I wonder if it should be const?
you must be forgetting the namespace
try - std::ostream &operator<<(std::ostream &out)

Storing values in a container

I'm trying to read two values from a file and store them in my class called God. God has two data members, name and mythology. I wish to store the values in a list<God> (the god and its respective mythology) and then print them out. Here is my code so far:
#include <iostream>
#include <fstream>
#include <list>
#include <string>
using namespace std;
class God {
string name;
string mythology;
public:
God(string& a, string& b) {
name=a;
mythology =b;
}
friend ostream& operator<<( ostream& os,const God&);
};
void read_gods(list<God>& s) {
string gname, gmyth;
//reading values from file
ifstream inFile;
inFile.open("gods.txt");
while(!inFile.eof()) {
inFile >> gname >> gmyth ;
s.push_back(God(gname, gmyth));
}
}
ostream& operator<<( ostream& os,const God& god) {
return os << god.name << god.mythology;
}
int main() {
//container:
list<God> Godmyth;
read_gods(Godmyth);
cout << Godmyth;
return 0;
}
If for example I read in Zeus, Greek then how would I be able to access them?
The error I'm receiving is:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|
You should write either operator << or some member function for class God that outputs its data members.
For example
class God
{
public:
std::ostream & out( std::ostream &os ) const
{
return os << name << ": " << mythology;
}
//...
};
Or
class God
{
public:
friend std::ostream & operator <<( std::ostream &, const God & );
//...
};
std::ostream & operator <<( std::ostream &os, const God &god )
{
return os << god.name << ": " << god.mythology;
}
In this case instead of invalid statement
cout << Godmyth << endl;
you could write
for ( const God &god : Godmyth ) std::cout << god << std::endl;
Or if you simply want to access the data members then you should write getters.
For example
class God
{
public:
std::string GetName() const { return name; }
std::string GetMythology() const { return mythology; }
//...
There is no overloaded operator<< allowing printing std::list's content using std::cout.
What you can do?
As #Vlad mentioned, you can write
for ( const God &god : Godmyth )
std::cout << god << '\n';
Alternatively, you can write your own operator<<:
template<typename T>
std::ostream& operator<< (std::ostream &os, const std::list<T> &_list){
os << "[\n";
for ( const auto &item : _list )
os << item << ";\n";
return os << ']';
}

Operator Overloading: Ostream/Istream

I'm having a bit of trouble with a lab assignment for my C++ class.
Basically, I'm trying to get the "cout << w3 << endl;" to work, so that when I run the program the console says "16". I've figured out that I need to use an ostream overload operation but I have no idea where to put it or how to use it, because my professor never spoke about it.
Unfortunately, I HAVE to use the format "cout << w3" and not "cout << w3.num". The latter would be so much quicker and easier, I know, but that's not my decision since the assignment necessitates I type it in the former way.
main.cpp:
#include <iostream>
#include "weight.h"
using namespace std;
int main( ) {
weight w1(6);
weight w2(10);
weight w3;
w3=w1+w2;
cout << w3 << endl;
}
weight.h:
#ifndef WEIGHT_H
#define WEIGHT_H
#include <iostream>
using namespace std;
class weight
{
public:
int num;
weight();
weight(int);
weight operator+(weight);
};
#endif WEIGHT_H
weight.cpp:
#include "weight.h"
#include <iostream>
weight::weight()
{
}
weight::weight(int x)
{
num = x;
}
weight weight::operator+(weight obj)
{
weight newWeight;
newWeight.num = num + obj.num;
return(newWeight);
}
TL;DR: how can I make the "cout << w3" line in main.cpp work by overloading the ostream operation?
Thanks in advance!
Make a friend function in your class
friend ostream & operator << (ostream& ,const weight&);
define it as :
ostream & operator << (ostream& os,const weight& w)
{
os<<w.num;
return os;
}
See here
class weight
{
public:
int num;
friend std::ostream& operator<< (std::ostream& os, weight const& w)
{
return os << w.num;
}
// ...
};
Alternately, make a to_string method that converts weight.num to string ;-)