I was just learning about friend classes and overloading operators in C++ where I came upon an issue where I cannot access the private variables in the friend class. I'm almost sure this has to do with the fact we were required to have each file separate (Header, .cpp and main). Need some fresh eyes.
// Contents of Percent.h
#ifndef PERCENT_H
#define PERCENT_H
#pragma once
class Percent
{
// friend const Percent operator >>(Percent& first, Percent& second);
public:
friend bool operator ==(const Percent& first,
const Percent& second);
friend bool operator <(const Percent& first,
const Percent& second);
Percent();
friend istream& operator >>(istream& inputStream,
Percent& aPercent);
friend ostream& operator <<(ostream& outputStream,
const Percent& aPercent);
//There will be other members and friends.
private:
int value;
};
// Contents of Percent.cpp
#include <iostream>
#include "Percent.h"
using namespace std;
istream& operator >>(istream& inputStream,
Percent& aPercent)
{
char percentSign;
ERROR HERE - Cannot access value
inputStream >> aPercent.value;
inputStream >> percentSign;
return inputStream;
}
ostream& operator <<(ostream& outputStream,
const Percent& aPercent)
{
outputStream << aPercent.value << '%';
return outputStream;
}
#endif // !PERCENT_H
// Main.cpp
not written yet
Related
I am trying to write out a class called WholeNumber. I am not finished writing it, I like to try to compile frequently so I can keep the errors low and manageable. When I go to compile the class as it is I get this error:
fibonacci.cpp: In member function ‘std::__cxx11::list& WholeNumber::operator=(WholeNumber&)’:
fibonacci.cpp:41:14: error: invalid initialization of reference of type ‘std::__cxx11::list&’ from expression of type ‘WholeNumber’
return *this;
I've tried looking up the error to see if I could find the answers to my problem, but I could only find that you can't initialize a non-const reference from a const reference. I don't understand what that could be referring to my code. What am I missing?
#include <iostream>
#include "fibonacci.h" // for fibonacci() prototype
#include <list>
#include <vector>
using namespace std;
class WholeNumber
{
private:
list <int> digits;
public:
//default constructor
WholeNumber() { }
//non-default constructor
WholeNumber(unsigned int number) {number = 0;}
//copy constructor
WholeNumber(const WholeNumber & rhs) { }
//destructor
~WholeNumber() { }
friend ostream & operator << (ostream & out, const list <int> * l);
istream & operator >> (istream & in);
WholeNumber & operator +=(const WholeNumber & rhs);
list <int> & operator = (WholeNumber & rhs)
{
this->digits = rhs.digits;
return *this;
}
};
The returned type of the copy assignment operator is list <int> &
list <int> & operator = (WholeNumber & rhs)
{
this->digits = rhs.digits;
return *this;
}
but an object of the type WholeNumber (*this) is returned and there is no implicit conversion from one type to another.
Maybe you mean the following
WholeNumber & operator = ( const WholeNumber & rhs )
{
this->digits = rhs.digits;
return *this;
}
Also these operators
friend ostream & operator << (ostream & out, const list <int> * l);
istream & operator >> (istream & in);
are invalid. For example the first operator should be declared like
friend ostream & operator << (ostream & out, const WholeNumber & );
And the second operator also should be a friend function like
friend istream & operator >> ( istream & in, WholeNumber & );
I am new to C++ programming and am having trouble implementing this operator overloading. It gives the error that no operator "<<" matches these operands.
class class1{
public:
bool operator==(class1 &);
friend ostream & operator<<(ostream &, class1 &);
private:
string name;
};
/*Friend ostream & operator <<*/
ostream & operator << (ostream & os, class1 & obj){
os << obj.name;
return os;
}
Someone mentioned I need another overloaded operator, but I can't figure out how to make it work with another overloaded operator
Here is the situation with your code; you have a private member string variable within your class where no outside object can set this variable. Your class does not contain a defined constructor nor a setting method. When I tried your code I had to change your operator declaration and definition from this:
std::ostream& operator<<( std::ostream& os, class1& obj );
to this:
std::ostream& operator<<( std::ostream& os, const class1& obj );
in order for it to compile. However when it came to building the project I was getting a Linker Error of an unresolved identifier. What was happening here is that the ostream object that you are declaring as a friend to your class object does know about the private member string but it can not do anything with it since this string is empty or not valid. I changed your class to this:
#include <conio.h>
#include <string>
#include <iostream>
class class1 {
friend std::ostream& operator<<( std::ostream& out, const class1& other );
private:
std::string m_strName;
public:
explicit class1( std::string& strName ) : m_strName( strName ) {}
void setName( std::string& strName ) { m_strName = strName; }
std::string getName() const { return m_strName; }
};
std::ostream& operator << ( std::ostream& out, class1& obj ) {
out << obj.m_strName << std::endl;
// out << obj.getName() << std::endl;
return out;
}
int main() {
class1 a( std::string( "class1" ) );
std::cout << a << std::endl;
std::cout << "Press any key to quit" << std::endl;
_getch();
return 0;
}
This compiles, builds, links and executes properly and displays appropriate text and exits with a value of 0 for no errors. I am using MSV2013 on a Win7 machine. The main issue was that since your class had no way to populate its string member upon construction the ostream operator object could not resolve the variable in use.
The overload operator<<(std::ostream&, std::string) is actually defined by #include <string>.
Although std::string is also defined by that header, it is still possible for std::string to be defined but not this operator overload, if you did not include that header.
The C++ standard requires that certain headers provide certain features, but it does not prohibit that feature also being provided by another header. In your case, the compiler/library writer has decided that implementing some other feature in another header was most easily done by defining std::string, but it would have done this by having a separate file defining std::string which is included both by <string> and by the other header.
remove the keyword "friend" for ostream if you intent for it to be a public member. If your want ostream to be friend move it above public:
operator== should have two const parameter, const if you do not intend to change.
friend ostream & operator<<(ostream &, const class1 &);
public:
bool operator==(const class1& x, const class1& y);
or
public:
bool operator==(const class1& x, const class1& y);
ostream & operator<<(ostream &, const class1 &);
make operator << second parameter a const might help
ostream & operator << (ostream & os, const class1 & obj){
os << obj.name;
return os;
}
My current code is not working.
I am trying to use << operator of Person class in the << operator of Student class. Is that possible?
#include <iostream>
using namespace std;
class Person
{
private:
int EGN;
public:
Person(int e):EGN(e){}
friend ostream& operator <<(ostream& out, const Person& p);
};
ostream& operator <<(ostream& out, const Person& p)
{
out<<p.EGN<<endl;
return out;
}
class Student: public Person
{
private:
int fn;
public:
Student(int e, int f):Person(e)
{
fn=f;
}
friend ostream& operator <<(ostream& out, const Student& p);
};
ostream& operator <<(ostream& out, const Student& p)
{
Person :: operator << (out,p);
out<<p.fn<<endl;
return out;
}
Person's operator << is a friend, not a member, so you can't access it using the :: operator.
Try casting your student to a person to call the right overload:
out << static_cast<const Person &>(p);
Problem Solved, thank you all for your help!
I've run into a problem that i can't seem to figure out.
I am trying to overload the ostream operator as a friend function in order to be able to print out the member data of that object, and i can't seem to get it to work.
This is what i got so far:
.h file:
Class TestIt:
{
public:
TestIt();
TestIt(int a, b);
friend ostream& operator <<(ostream& outputStream, const TestIt& a);
Private:
int NUMBER1;
int NUMBER2;
};
.cpp file:
ostream& operator <<(ostream& outputStream, const TestIt& a)
{
outputStream << a.NUMBER1 << " " << a.NUMBER2;
return(outputStream);
}
What i am trying to do is, pass in an object in ostream, then output its member data.
The error that i am receiving is that
"the member TestIt::NUMBER1 declared in TestIt.h is inaccessible.
and same error also exists with my other member data.
Why would that be?
Thank you for your help.
Here's a whole program that i just wrote, giving me the same error:
TestClass.cpp
#include "TestClass.h"
#include <iostream>
using namespace std;
TestClass::TestClass(int a, int b)
{
age = a;
whole = b;
}
int TestClass::GetAge() const
{
return(age);
}
ostream& operator <<(ostream& outputStream, const TestClass& t1)
{
t1.whole;
t1.age;
return(outputStream);
}
TestClass.h
#ifndef TestClass_H
#define TestClass_H
class TestClass
{
public:
TestClass(int a, int b);
int GetAge() const;
friend ostream& operator <<(ostream& outputStream, const TestClass& t1);
private:
int whole;
int age;
#endif
The operator<< that you've defined and the operator<< that you've friended aren't the same name. Are you using namespaces?
I'm trying to write a class that overloads the insertion operator but in my header file I get the error.
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
Here is my code:
.h file
ostream & operator<<(ostream & os, Domino dom);
.cpp file
ostream & operator<< (ostream & os, Domino dom) {
return os << dom.toString();
}
I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?
You probably put your operator<< inside a class declaration. That means it takes an extra hidden parameter (the this parameter). You need to put it outside of any class declaration.
The insertion operator (<<) can be used as a member function or a friend function.
operator << used as a member function
ostream& operator<<(ostream& os);
This function should be invoked as :
dom << cout;
In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.
operator << used as a friend function
friend ostream& operator<<(ostream& os, const Domino& obj);
This function should be invoked as :
cout << dom;
In this case the object dom is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.
/*insertion and extraction overloading*/
#include<iostream>
using namespace std;
class complex
{
int real,imag;
public:
complex()
{
real=0;imag=0;
}
complex(int real,int imag)
{
this->real=real;
this->imag=imag;
}
void setreal(int real)
{
this->real=real;
}
int getreal()
{
return real;
}
void setimag(int imag)
{
this->imag=imag;
}
int getimag()
{
return imag;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};//end of complex class
istream & operator >>(istream & in,complex &c)
{
int temp;
in>>temp;
c.setreal(temp);
in>>temp;
c.setimag(temp);
return in;
}
ostream &operator <<(ostream &out,complex &c)
{
out<<c.getreal()<<c.getimag()<<endl;
return out;
}
int main()
{
complex c1;
cin>>c1;
// c1.display();
cout<<c1;
//c1.display();
return 0;
}