Can I print an object of the class using printf()? - c++

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.

Related

printing an unordered map made by structs c++ [duplicate]

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;
}
};

How to custom ostream c++

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(?)

How do I make a class in C++ so that it acts like a native int class

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;
}

Function returning to ostream

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.

How can I write a variable of a user-defined type into a stream

I dont mean a variable in a class but a default value for the class as a whole.
struct Scalar {
unsigned int value;
void toThePowerOf(int power);
// etc.
}
I'd like to be able to do something like
Scaler foo;
foo.value = 2;
foo.toThePowerOf(2);
std::cout << foo << std::endl; // Outputs 4!
Is that possible in C++?
No, classes do not have a value in the way you're thinking.
What you probably mean to do is to overload the << operator:
ostream& operator<<(ostream& output, const Scalar& val)
{
output << val.value;
return output;
}
I meant a default value for the class, so if you called that object by just its name foo it would return foo.value by default.
It is actually possible to define an implicit conversion from Scalar to int:
struct Scalar
{
unsigned int value;
operator int() const
{
return value;
}
};
int main()
{
Scalar foo = {2};
std::cout << foo << std::endl;
}
But implicit conversions are generally frowned upon in the C++ community, because it can make code quite hard to read. (I guess this is why noone mentioned conversion operators yet.)
No, you cannot but you can overload operator << for your class and ostream to get the desired effect
std::ostream& operator << (std::ostream& out, const Scaler& foo)
{
return out << foo.value;
}
Your code will now work and produce the desires result
Yes. it is possible. Just initialize all the values in the constructor of the class. Use class instead of struct.
Use a default value in the ctor. Make the ctor explicit if you don't want implicit conversions.
struct Scalar {
unsigned int value;
Scalar(int value=0) : value (value) {}
void toThePowerOf(int power) {
// naive implementation just for show
int new_value = 1;
assert(power >= 0); // or other error checking
for (; power > 0; --power) {
new_value *= value;
}
value = new_value;
}
friend std::ostream& operator<<(std::ostream &out, Scalar const &x) {
out << x.value;
return out;
}
};