In the main,
int main(){
Data s1(0, 2, 3);
Data s2(0, 2, 4);
cout << ((s1 == s2)? "Does" : "Doesn't") << "work" << endl;
}
In the h file I overloaded the << sign as a friend.
class Data{
private:
struct num{
int x, y, z;
};
num p;
public:
Data();
Data(int a, int b, int c);
//the question is to implement this function.
friend std::ostream& operator<< (std::ostream& outputStream, bool compare);
}
Normally, I write the function in cpp file like this (when not dealing with boolean)
ostream& operator << (ostream& output, const Data& a){
output << a.data << "data message" << endl;
return output;
}
So how would you implement the friend overload function if it's like the "weird" way of writing boolean expression?
You don't need to provide std::ostream& operator<< (std::ostream&, bool). The standard library already provides one.
Your problems is you haven't defined an operator overload function to evaluate s1 == s2. The error is from that missing function.
Update your class by adding the following member function
bool operator==(Data const& rhs) const;
if you really need to use the expression s1 == s2.
Here's a demonstrative program:
#include <iostream>
class Data{
private:
struct num{
int x, y, z;
};
num p;
public:
Data() {}
Data(int a, int b, int c) {}
bool operator==(Data const& rhs) const { return true; }
};
int main()
{
Data s1(0, 2, 3);
Data s2(0, 2, 4);
std::cout << ((s1 == s2)? "Does" : "Doesn't") << "work" << std::endl;
}
and its output
Doeswork
PS
Please note that you have to implement the functions properly to make the class useful.
Related
I want to overload the stream insertion operator for a structure nested within a class. How can I fix this error and make the function to work, or is there any alternative method to implement it?
struct S {
int a;
int b;
};
class T {
private:
S** arrayName;
int r;
int c;
public:
friend ostream& operator << (ostream& _os, const T& _t) {
for (int i = 0; i < _t.r; i++) {
for (int j = 0; j < _t.c; j++) {
_os << _t.arrayName[i][j];
}
}
return _os;
}
}
If arrayName was just an integer array within class T like:
int arrayName [4][4]; //for example
the current implementation would work. But as arrayName is a pointer to pointer to struct S and acts as a two-dimensional array of struct S, you will need to overload the << operator within struct S to be able to print its members a and b.
So your struct S should now be:
struct S {
int a;
int b;
friend ostream& operator<<(ostream& _os, const S& _s) {
_os << _s.a << ' ' << _s.b << endl;
return _os;
}
};
I have a simple Node class that creates Nodes and can access the strings inside these Nodes. I have two operator overloading functions in the class in order to be able to compare the Nodes ( > overloader) and print their data ( << overloader). There is also templated copy of the built in max() function. Both of my operator overloaders work as they should, except when I try to print the return value of the max() function with two Nodes as parameters. Here is my code:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
T maximum(const T& a, const T& b){
return a > b ? a : b;
}
class Node{
public:
Node(const string& s = "Default"):
data(s){
}
string get_data() const {
return this->data;
}
friend ostream& operator << (ostream& os, Node& a){
return os << a.get_data();
}
friend bool operator > (const Node& a, const Node& b){
if(a.get_data() > b.get_data()){
return true;
}
else return false;
}
private:
string data;
Node* next;
};
int main() {
double d1 = 0.1, d2 = 0.2;
cout << maximum(d1, d2) << endl;
string s1 = "woody", s2 = "buzz";
cout << maximum(s1, s2) << endl;
Node a("buzz"), b("woody");
cout << maximum(a, b) << endl;
return 0;
}
The problem lies in the last line of the main() function. My compiler throws an error message saying something similar to cannot bind ostream<char> value to ostream<char>&&
Add const to second argument of operator<<:
friend ostream& operator << (ostream& os, const Node& a){
^^^^^
I have a class A, for which I have defined an (overloaded) stream insertion operator. I publicly derive a class B from this class A, which has an additional data member. Therefore I'll need to redefine the overloaded stream insertion operator for the derived class and I've do it this way:
#include <iostream>
using namespace std;
class A {
int i;
char c;
public:
A(int i = 0, char c = ' ') {
this->i = i;
this->c = c;
}
friend ostream& operator << (ostream&, const A&);
};
class B : public A {
double d;
public:
B(int i = 0, char c = ' ', double d = 0.0) : A(i, c), d(d) {}
friend ostream& operator << (ostream&, const B&);
};
ostream& operator << (ostream& out, const A& a) {
out << "\nInteger: " << a.i << "\nCharacter: " << a.c << endl;
return out;
}
ostream& operator << (ostream& out, const B& b) {
out << b;
out << "\nDouble: " << b.d << endl;
return out;
}
int main() {
A a(10, 'x');
B b(20, 'y', 5.23);
cout << b;
return 0;
}
Question-1: Is this an appropriate technique of doing so? If not, kindly let me know where I'm going wrong.
Question-2: On running, this program crashes. Why so?
One common way to support this is to have the overloaded operator invoke a virtual member function:
class A {
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
os << "A\n";
return os;
}
};
class B : public A {
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
// This can use the base class writer like:
A::write(os);
os << "B\n";
return os;
}
};
Then the operator overload just invokes that member function:
std::ostream &operator<<(std::ostream &os, A const &a) {
return a.write(os);
}
Since write is virtual and you're passing the A by (const) reference, this invokes the correct member function based on the actual type (i.e., A::write if the object is really an instance of A, and B::write if it's an instance of B).
For example, we could exercise these something like this:
int main() {
A a;
B b;
std::cout << a << "\n";
std::cout << b << "\n";
}
...which produces output like this:
A
A
B
In real use, you probably want to make the write functions protected, and make the operator<< a friend of A.
The program crashes because your second insertion operator calls itself:
ostream& operator << (ostream& out, const B& b) {
out << b; // <--YIKES!
out << "\nDouble: " << b.d << endl;
return out;
}
Generally this is a good approach, although I prefer to give the classes a public virtual print(ostream&) const function, and have the insertion operator call that.
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'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could override the toString() method for similar purpose.
In C++ you can overload operator<< for ostream and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
You can also do it this way, allowing polymorphism:
class Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Base: " << b << "; ";
}
private:
int b;
};
class Derived : public Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Derived: " << d << "; ";
}
private:
int d;
}
std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }
In C++11, to_string is finally added to the standard.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:
#include <sstream>
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace
std::stringstream is located in the <sstream> header.
The question has been answered. But I wanted to add a concrete example.
class Point{
public:
Point(int theX, int theY) :x(theX), y(theY)
{}
// Print the object
friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
int x;
int y;
};
ostream& operator <<(ostream& outputStream, const Point& p){
int posX = p.x;
int posY = p.y;
outputStream << "x="<<posX<<","<<"y="<<posY;
return outputStream;
}
This example requires understanding operator overload.