Why doesn't this work?
I use friendly function in my code but there is an error so I can not find it. please help.
#include<iostream>
#include<cstdlib>
using namespace std;
class Circle{
private:
int x;
public:
Circle(int x1=5){
x=x1;
friend std:ostream & operator<<(const Circle & c, std::ostream & os)
{
return os<<c.x
}
}
};
int main()
{
Circle s;
cout<< s;
system("pause");
return 0;
}
Four problems:
You've defined the friend function inside the constructor. Move it outside so that it's its own function.
Replace std:ostream with std::ostream
Swap the order of the parameters.
Add a semicolon after return os<<c.x
Final result:
class Circle{
private:
int x;
public:
Circle(int x1=5){
x=x1;
}
friend std::ostream & operator<<(std::ostream & os, const Circle & c)
{
return os<<c.x;
}
};
friend std:ostream & operator<<(const Circle & c, std::ostream & os)
{
return os<<c.x
}
you should declare this function outside the constructor.
The friend function needs to be declared at the same level as the constructor, not inside it.
Related
I tried to make friend ostream function. The compiler say i cannot access private member of the class, even though i declared it as friend. I read a similar question and it say the problem is with the namespcaes.(the question: C++ friend function can't access private members)
My Code is below:
header:
#include <iostream>
#include <string>
//using namespace std;
namespace biumath
{
#ifndef BIUMATH_H
#define BIUMATH_H
class Assignment
{
private:
int **m_varArray;
int m_rowsOfVarArray;
public:
Assignment(); //1
Assignment(char symbol, double value); //2
bool containsValueFor(char symbol) const; //3
double valueOf(char symbol) const; //4
void add(char symbol, double val); //5
friend std::ostream& operator<< (std::ostream& out,
const Assignment& assignment);
};
}
#endif
cpp:
#include <iostream>
#include "biumath.h"
using namespace biumath;
using std::cout;
using std::endl;
ostream& operator<< (ostream& out,
const Assignment& assignment){
out<<assignment.m_rowsOfVarArray<<std::endl;
//return the stream. cout print the stream result.
return out;
}
or better yet, avoid all unnecessary friendships by deferring to a public utility method (this also has benefits when your Assignment is a polymorphic base class):
in header file:
namespace biumath
{
class Assignment
{
private:
int **m_varArray;
int m_rowsOfVarArray;
public:
Assignment(); //1
Assignment(char symbol, double value); //2
bool containsValueFor(char symbol) const; //3
double valueOf(char symbol) const; //4
void add(char symbol, double val); //5
void write(std::ostream& os) const; // <=== public helper
};
// free function overload which defers to helper.
// NOTE: it's in the biumath namespace so ADL will find it
inline std::ostream& operator<< (std::ostream& out,
const Assignment& assignment){
assignment.write(out);
return out;
}
}
in CPP file:
namespace biumath {
void Assignment::write(std::ostream& os) const {
os << m_rowsOfVarArray << std::endl;
}
}
You may define the operator in the enclosing namespace (in your case in the global namespace) but you have to use the qualified name.
Thus define the operator like
ostream& biumath::operator<< (ostream& out,
const Assignment& assignment){
out<<assignment.m_rowsOfVarArray<<std::endl;
//return the stream. cout print the stream result.
return out;
}
Only you also have at first to declare the operator in the same namespace where the class is defined.
If you want that the operator would be declared in the global namespace then you can do it the following way
namespace biumath
{
class Assignment;
}
std::ostream& operator<< ( std::ostream &,
const biumath::Assignment & );
namespace biumath
{
class Assignment
{
//...
friend std::ostream& ::operator<< (std::ostream& out,
const Assignment& assignment);
};
}
You've befriended an operator in your biumath namespace, but you don't define that; instead you define a separate operator in the global namespace.
Re-open the namespace in the source file, and put the definition inside it.
I was wondering if there is any way to overload the << operator for a class without declaring it as a friend function. My professor said this is the only way to do it, but I wanted to know if there is another way that he was unaware of.
There is no need to make the operator<< function a friend of the class as long as everything you want to be output is accessible through the public interface of the class.
You need to declare it is as friend function if and only if you need access to it's private members.
You can always do this without using friend function if:
1) No private member access is required.
2) You provide a mechanism to access your private member otherwise. e.g.
class foo
{
int myValue;
public:
int getValue()
{
return myValue;
}
}
Yes, you can
std::ostream& operator<<(std::ostream &stream, WHATEVER_TYPE var) {
std::string str = somehowstringify(var);
return stream << str;
}
Note however that by virtue of it being a non-member non-friend function it can of course only access the public interface of std::ostream, this usually isn't a problem.
Yes, one way to do it is like this:
class Node
{
public:
// other parts of the class here
std::ostream& put(std::ostream& out) const { return out << n; };
private:
int n;
};
std::ostream& operator<<(std::ostream& out, const Node& node) {
return node.put(out);
}
As R Sahu has pointed out, the requirement is that the operator should be able to access everything it has to display.
Here are a few possible options
1.Adding the overloaded function as a friend function
2.Making all the required data members of the class accessible for the function using either public accessor methods or public data members
class MyClass {
private:
int a;
int b;
int c;
public:
MyClass(int x,int y,int z):a(x),b(y),c(z) {};
MyClass():a(0),b(0),c(0) {};
int geta() { return a; }
int getb() { return b; }
int getc() { return c; }
};
std::ostream& operator<<(std::ostream &ostr,MyClass &myclass) {
ostr << myclass.geta()<<" - " << myclass.getb() << " - " << myclass.getc() ;
return ostr;
}
int main (int argc, char const* argv[])
{
MyClass A(4,5,6);
cout << A <<endl;
return 0;
}
3.Add a public helper function , say output with the signature std::ostream& output(std::ostream& str) and use it later in the operator function.
I am learning C++, and learned that int-types are just premade classes. So I thought maybe i should try to create one.
What I want to do basically is a
normal class of int
int x;
x=7;
cout << x;
// Output is 7 on screen.
so similarly...
abc x;
x=7;
cout << x;
What would I put in
class abc{
\\ HERE!!!!!!
};
so I could do this
class SomeClass {
public:
int x;
SomeClass(int x) {
this->x = x;
}
};
int main(int argc, char *argv[]) {
SomeClass s = 5;
cout << s.x << "\n"; // 5
s = 17;
cout << s.x << "\n"; // 17
return 0;
}
But as you can see I have to use s.x to print the value - I just want to use 's'.
I am doing it as an experiment, I don't want to hear about how this method is good or bad, pointless or revolutionary, or can 't be done. I remember once I did it. But only by copying and pasting code that I didn't fully understand, and have even forgotten about.
and learned that int, types, are just premade classes
This is completely false. Still, you have complete control on how your class will behave in expressions, since you can overload (almost) any operator. What you are missing here is the usual operator<< overload that is invoked when you do:
cout<<s;
You can create it like this:
std::ostream & operator<<(std::ostream & os, const SomeClass & Right)
{
Os<<Right.x;
return Os;
}
For more information, see the FAQ about operator overloading.
the << and >> are basically function names. you need to define them for your class. same with the +, -, * and all the other operators. here is how:
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
You need to overload operator<< for your class, like so:
class abc
{
public:
abc(int x) : m_X(x) {}
private:
int m_X;
friend std::ostream& operator<<(std::ostream& stream, const abc& obj);
};
std::ostream& operator<<(std::ostream& os, const abc& obj)
{
return os << obj.m_X;
}
You don't have to friend your operator<< overload unless you want to access protected/private members.
You must define in your class abc cast operator to int and assignment operator from int, like in this template class:
template <class T>
class TypeWrapper {
public:
TypeWrapper(const T& value) : value(value) {}
TypeWrapper() {}
operator T() const { return value; }
TypeWrapper& operator (const T& value) { this->value = value; return *this; }
private:
T value;
};
int main() {
TypeWrapper<int> x;
x = 7;
cout << x << endl;
}
You want to overload the output operator:
std::ostream& operator<< (std::ostream& out, SomeClass const& value) {
// format value appropriately
return out;
}
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;
}