I wonder if there is any possibility to create function returning some part of ostream, like in example:
#include <iostream>
class Point {
public:
Point(int x, int y){
this->x = x;
this->y = y;
}
?? getXY(){ // I wish this function returned ostream
return ??;
}
private:
int x,y;
};
int main() {
Point P(12,7);
std::cout << "(x,y) = " << P.getXY(); // (12, 7);
}
I wish the output was:
(x,y) = (12,7)
I don't want getXY() to return any string or char array. May I somehow return part of stream?
Generally this is done by overloading the stream insertion operator for your class, like this:
class Point {
public:
Point(int x, int y){
this->x = x;
this->y = y;
}
int getX() const {return x;}
int getY() const {return y;}
private:
int x,y;
};
std::ostream& operator<<(std::ostream& out, const Point& p)
{
out << "(x,y) =" << p.getX() << "," << p.getY();
return out;
}
Used as:
Point p;
cout << p;
Why not just implement operator << for your class? It would do exactly what you want.
If you only need to print one sort of output, just override operator<< in your containing class. But, if you need to print different sorts of output according in different contexts, you might try creating objects of different proxy classes.
The proxy object could hold a reference to Point, and print it (or portions of it) according to your needs.
I would make the proxy objects private member classes of Point to restrict their visibility.
EDIT Removed sample -- I didn't notice this was homework.
In addition to your Point code, you can use a helper function (below, display()) as an alternative to overloading:
std::ostream& display(std::ostream &os,Point &p) const {
os<< p.x << p.y ;
return os;
}
int main() {
Point p;
display(std::cout,p);
// This will call the display function and
// display the values of x and y on screen.
} //main
The display function can be made a friend of class Point if it needs to access private members.
Related
This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 10 months ago.
I have a Point class that represents a point in 2d plane. I have written a simple operator + member function . I am able to add two objects of the class Point , but not three.
Why cant I add 3 objects in one line?
The following code works perfectly -:
Point p(1,2) , q(3,4);
Point r = p+q;
cout<<p+q;
The following code gives an error;
Point w = p+q+r;
Error - ‘Point’ is not derived from ‘const std::reverse_iterator<_Iterator>’
Below is my implementation
class Point{
int x;
int y;
static int count ;
public:
Point() :x(0) , y(0) {count++;}
Point(int x,int y){this->x = x; this->y =y; count++;}
~Point(){ count--; }
int getx() { return x ; }
int gety() { return y ; } // can const objects call these functions.. check
void setx( int x) { this->x = x;}
void sety( int y) { this->y = y;}
friend Point operator +(Point &, Point &);
friend std::ostream & operator << (std::ostream &,Point );
};
int Point::count = 0;
Point operator +(Point &p,Point &q) // check if const p can be passed
{
Point sum(q.getx() + p.getx(), q.gety() + p.gety());
return sum;
}
std::ostream & operator << (std::ostream &os,Point p)
{
os<<"("<<p.getx()<<","<<p.gety()<<")";
return os;
}
An operator+ cannot be overloaded for three parameters. If you want to add three classes together you need a separate function of the Three parameters of the class data type. Like :
Point sum(Point&a , Point&b , Point&c)
{
Point sum ;
int x= a.getx() + b.getx() + c.getx() ;
sum.setx(x);
int y= a.gety() + b.gety() + c.gety() ;
sum.sety(y);
return sum;
}
i have a class:
class Y{
public:
int x;
Y();
};
Main:
int main(){
Y y;
y.x = 10;
y << mystream;
return 0;
}
I just wanna to cause any action when y<<mystream is typed.
I tried in my class header like those:
friend Y mystream(Y y);
friend ostream mystream(ostream o, Y y)
And etc. but nothing didn't work. Any ideas to custom this stream?
Best regards!
You can overload the insertion operator "<<" to take a class A object as its LHS and an ostream object as its rhs:
class A{
public:
int x;
friend ostream& operator << (A& lhs, ostream& out){
out << lhs.x;
return out;
}
};
int main(){
A a;
a.x = 7;
a << cout; // 7
cout << endl;
return 0;
}
You have to overload the '<<' operator in the class then you can use it for custom output stream. Also when passing the object of ostream, make sure that they are passed by reference. You can refer to this site for example http://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/
I dont't need:
A a;
cout<<a;
// or
a<<cout;
For example I can do this for cout in main:
ostream& cause(ostream& out)
{
out<<"My stream is here";
return out;
}
int main()
{
cout<<cause; // Print here 'my stream is here'
return 0;
}
I just wanna get this behaviour for my class instead of std::cout, so i wanna write in main:
A a;
a<<cause; // i want to manipulate stream(?)
I have some code like this:
class Point {
public:
int x,y;
Point() : x(1), y(1) {}
}
Can I print object of that class using printf():
int main()
{
Point point;
printf("%o",point);
return 0;
}
or I have to overload operator<< and use std::cout:
std::ostream& operator<<(std::ostream& os, Point const& p)
{
os << p.x << "," << p.y;
return os;
}
int main()
{
Point point;
std::cout << point;
return 0;
}
Can I print object of that class using printf()?
No. printf is not extensible in that sense.
Your best option is to overload operator<< between std::ostream and Point.
PS I suggest changing the argument type to Point const&.
You can however, use a custom print function in your class, that would print your object the way you want:
...
void print() const {
printf("[%d, %d]", x, y);
}
...
int main()
{
Point point;
point.print();
return 0;
}
You can also use fprintf and a custom stream if you want to. This is not entirely an answer to your question, but seems to be useful in the described situation.
You must have to overload the operator otherwise , the printf() will get confused what to print of the object point as the class has two members.
#include <iostream>
using namespace std;
class family
{
private:
double weight;
double height;
public:
family(double x,double y);
~family();
double getWeight();
double getHeight();
double setWeight();
double setHeight();
bool operator==(const family &)const;
};
bool family::operator ==(const family &b)const
{
return weight==b.weight;
}
family::family(double x, double y)
{
weight = x;
height = y;
}
double family::getWeight()
{
return weight;
}
double family::getHeight()
{
return height;
}
family::~family(){}
int main()
{
family a(70.0,175.2);
family b(68.5,178.2);
if(a==b)
cout << "A is bigger than B" << endl;
else
cout << "A is smaller than B" << endl;
return 0;
}
Above the code, I can implement operator overloading with member function. However, I failed to implement operator overloading with non member function. How should i modify this code b.b
Please help me..
Basically, the only difference between a member function and a non-member function is that it's passed an implicit this pointer as well as any other arguments and it has access to private/protected members. So to transform any member function to a non-member function is to simply factor it out of the class definition. make it a friend of that class and add a parameter that's a reference to that class. Pass in an object of that class when you call it. You can also do a const& of the function.
You can use Friend Function and use objects as parameter of that function like we use in << operator.
we also can use operator without friend function :
bool operator==(const family first, const family second)
{
if(first.getWeight( ) == second.getWeight( )){
return True;
else
return False;
}
class family
{
private:
double weight;
double height;
public:
family( double x, double y );
~family( );
// getters should be const
double getWeight( ) const;
double getHeight( ) const;
double setWeight( );
double setHeight( );
};
// no reason to make it friend of class
// b/c it does not work with private/protected members
bool operator==( const family & first, const family & second );
// better to move into cpp file
bool operator==( const family & first, const family & second )
{
return first.getWeight( ) == second.getWeight( );
}
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;
}