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(?)
Related
myclass is a C++ class written by me and when I write:
myclass x;
cout << x;
How do I output 10 or 20.2, like an integer or a float value?
Typically by overloading operator<< for your class:
struct myclass {
int i;
};
std::ostream &operator<<(std::ostream &os, myclass const &m) {
return os << m.i;
}
int main() {
myclass x(10);
std::cout << x;
return 0;
}
You need to overload the << operator,
std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
os << obj.somevalue;
return os;
}
Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.
If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.
it's very easy, just implement :
std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
os << foo.var;
return os;
}
You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)
Even though other answer provide correct code, it is also recommended to use a hidden friend function to implement the operator<<. Hidden friend functions has a more limited scope, therefore results in a faster compilation. Since there is less overloads cluttering the namespace scope, the compiler has less lookup to do.
struct myclass {
int i;
friend auto operator<<(std::ostream& os, myclass const& m) -> std::ostream& {
return os << m.i;
}
};
int main() {
auto const x = myclass{10};
std::cout << x;
return 0;
}
Alternative:
struct myclass {
int i;
inline operator int() const
{
return i;
}
};
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.
Ok so I am trying to write a template that builds a 2D matrix, and I want the >> and << to work as normal, here is the code I have so far but I am lost. I have functions input and output to run a user through filling the template at the moment, so I want to be able to cin and cout the template.
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T >
class Matrix
{
friend ostream &operator<<(ostream& os,const Matrix& mat);
friend istream &operator>>(istream& is,const Matrix& mat);
private:
int R; // row
int C; // column
T *m; // pointer to T
public:
T &operator()(int r, int c){ return m[r+c*R];}
T &operator()(T a){for(int x=0;x<a.R;x++){
for(int z=0;z<a.C;z++){
m(x,z)=a(x,z);
}
}
}
~Matrix();
Matrix(int R0, int C0){ R=R0; C=C0; m=new T[R*C]; }
void input(){
int temp;
for(int x=0;x<m.R;x++){
for(int y=0;y<m.C;y++){
cout<<x<<","<<y<<"- ";
cin>>temp;
m(x,y)=temp;
}
}
}
};
// istream &operator>>(istream& is,const Matrix& mat){
// is>>mat
// };
ostream &operator<<(ostream& os,const Matrix& mat){
for(int x=0;x<mat.R;x++){
for(int y=0;y<mat.C;y++){
cout<<"("<<x<<","<<y<<")"<<"="<<mat.operator ()(x,y);
}
}
};
int main()
{
Matrix<double> a(3,3);
a.input();
Matrix<double> b(a);
cout<<b;
cout << a(1,1);
}
Here are all the problems I found with your code. Let's start from the beginning:
Wrong function return-type and assignment through this
T operator>>(int c)
{
this = c;
}
Why is this code wrong? Well the first thing I notice is that your function is returning T yet you have no return statement present in the block. Forget about what I said in the comments, your insertion/exertion operators should return *this. It follows that your return-type should be Maxtrix&.
Another error I see in this snippet is that you are assigning the this pointer. This shouldn't have compiled for you. Rather, if you meant to change a certain data member (preferably your C data member), it should have looked like this:
this->C = c;
In turn, this is what your function should look like:
Matrix& operator>>(int c)
{
this->C = c;
return *this;
}
this->(z, x)
In the inner for loop of your output function, you did this:
cout << "(" << z << "," << x << ")" << "=" << this->(z, x) << endl;
this->(z, x) isn't doing what you think. It doesn't concurrently access two of the matrix's data members. It will actually cause an error because of invalid syntax. You'll have to access the data members separately, like this:
... << this->z << this->x << endl;
Moreover, this output function doesn't need a return-type. Just make it void.
Note that you have the same problem in your input 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;
}
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.