C++ Template >> and << overloading trouble - c++

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.

Related

Overloading << sign follow by a boolean expression

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.

no operator "<<" matches these operands when using operator overloading

Error ocurred with the following try to operator overloading:
#include<iostream>
#include<string>
#include<ostream>
using namespace std;
class Dollar
{
private:
float currency, mktrate, offrate;
public:
Dollar(float);
float getDollar() const;
float getMarketSoums() const;
float getofficialSoums() const;
void getRates();
// In the following function I was trying to overload "<<" in order to print all the data members:
friend void operator<<(Dollar &dol, ostream &out)
{
out << dol.getDollar() << endl;
out << dol.getMarketSoums() << endl;
out << dol.getofficialSoums() << endl;
}
};
Dollar::Dollar(float d)
{
currency = d;
}
float Dollar::getDollar() const
{
return currency;
}
float Dollar::getMarketSoums() const
{
return mktrate;
}
float Dollar::getofficialSoums() const
{
return offrate;
}
void Dollar::getRates()
{
cin >> mktrate;
cin >> offrate;
}
int main()
{
Dollar dollar(100);
dollar.getRates();
// In this line I am getting the error. Could you please help to modify it correctly?
cout << dollar;
system("pause");
return 0;
}
You have to pass std::ostream object as the first parameter to the insertion operator << not as the second one as long as you are calling it that way:
friend void operator << (ostream &out, Dollar &dol);
You should make the object passed in to the insertion operator constant reference as long as this function is only prints and not intending to modify the object's members:
friend void operator << (ostream &out, const Dollar& dol);
So pass by reference to avoid multiple copies and const to avoid unintentional modification.
If you want to invoke to get it work the way you wanted you can do this:
friend void operator<<(const Dollar &dol, ostream &out){
out << dol.getDollar() << endl;
out << dol.getMarketSoums() << endl;
out << dol.getofficialSoums() << endl;
}
And in main for example:
operator << (dollar, cout); // this is ok
dollar << cout; // or this. also ok.
As you can see I reversed the order of calling the insertion operator to match the signature above. But I don't recommend this, it is just to understand more how it should work.

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

Pass this to overloaded << operator

How can I pass this to operator<< in c++ class? Or am I just doing this wrong (likely).
For example, in the following class I just have a loop that repetitively asks for and prints an integer. However, cout<<this just prints the address of the instance, but I would like to use the defined operator overload.
#include<iostream>
using std::cout; using std::endl; using std::cin;
class C {
int n;
public:
C(int n) : n(n) {};
friend std::ostream& operator<<(std::ostream&, const C&);
void set_n(int i) { n = i; }
void play() {
int input;
while (true) {
cout << this;
cin >> input;
set_n(input);
}
}
};
std::ostream& operator<<(std::ostream& os, const C& c) {
cout << c.n << "\n";
return os;
}
int main(int argc, char *argv[]) {
C c = C(1);
c.play();
return 0;
}
this is a pointer. You need
cout << *this;
Also, your definition of operator<< should probably use the parameter os rather than always using cout.
this is a pointer. You probably need to dereference it.
cout << *this;

OOP C++ first compiler error

Please help this newbie, here's my code:
#include <iostream>
using namespace std;
class Complex {
private:
float r, i;
public:
Complex(float rr, float ii) : r(rr), i (ii) {}
float GiveRe () { return r; }
float GiveIm () { return i; }
void Setit (float rr, float ii) {
r = rr;
i = ii;
}
};
Complex a(10, 20);
Complex sumit (Complex &ref) {
static Complex sum (0, 0);
sum.Setit(sum.GiveRe() + ref.GiveRe(), sum.GiveIm() + ref.GiveIm());
return sum;
}
int main () {
Complex sumvalue = sumit (a);
cout << sumvalue << endl;
return 0;
}
error: no match for 'operator<<' in 'std::cout << sumvalue'.
The program should output the sum of a complex number.
cout can't tell what you want to output, you need to specify the operator<< in the class or make it possible to implicitly convert your class to a compatible type.
http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/
Rudolf Mühlbauer's code as implemented in your class:
Add this somewhere within the class header:
friend ostream& operator<<(ostream& out, const Complex& compl);
and this below the header:
ostream& operator<<(ostream& out, const Complex& compl)
{
return out << compl.r << "/" << compl.i;
}
Implementation should be changed to suit your exact needs.
Complex doesn't have an operator <<
ostream& Complex::operator << ( ostream& os )
{
// use os << field/method here to out put
return os;
}
Also if complex can be displayed to console in different ways, then you should think of using methods to display instead of cout <<
void Complex::DisplayToConsole()
{
std::cout << r << " " << i << '\n';
}
You have to overload the "<<" operator for Complex type.
#include <iostream>
using namespace std;
class Complex {
private:
float r, i;
public:
Complex(float rr, float ii) : r(rr), i (ii) {}
float GiveRe () { return r; }
float GiveIm () { return i; }
void Setit (float rr, float ii) {
r = rr;
i = ii;
}
};
ostream& operator<<(ostream& os, Complex& c)
{
float i;
os<<c.GiveRe();
if(c.GiveIm() < 0){
os<<"-j"<<c.GiveIm()*(-1);
}else{
os<<"+j"<<c.GiveIm();
}
return os;
}
Complex a(10, 20);
Complex sumit (Complex &ref) {
static Complex sum (0, 0);
sum.Setit(sum.GiveRe() + ref.GiveRe(), sum.GiveIm() + ref.GiveIm());
return sum;
}
int main () {
Complex sumvalue = sumit (a);
cout << sumvalue << endl;
return 0;
}
A complete minimal example:
#include <iostream>
using namespace std;
class C {
public:
int r, l;
// if the operator needs access to private fields:
friend ostream& operator<< (ostream&, const C&);
};
ostream& operator << (ostream& stream, const C& c) {
stream << c.r << "--" << c.l;
return stream;
}
int main() {
C c;
c.l = 1;
c.r = 2;
cout << c << endl;
}
C++ allows you to define operators. The STL uses the << operator for output, and the whole istream/ostream class hierarchy uses this operator to input/output.
Operators are implemented as functions, but always follow a very specific syntax. As in the example, ostream& operator << (ostream&, const MYTYPEHERE&) is the way to define ostream << operators.
When C++ encounters a statement, it has to deduce the types of all operands, and find (quite magically, indeed) a solution to the question: given my operands and operators, can i find a typing such that the statement gets valid?
These ofstream operators are defined for all basic types somewhere in <iostream>, so if you write cout << 10, the compiler finds an operator ostream& operator<< (ostream&, int).
If you want to be able to use userdefined types in this game, you have to define the operators. otherwise, a statement cout << sometype will not be valid. This is also the reason for the harsh compiler errors sometimes found in C++: "Well, i have some operators << defined, but none is compatible with your type!".
Because sometimes it is not favourable to implement operators for your types (if you only output them once, e.g.), i suggested to write:
cout << sum.re << "--" << sum.im << endl; // or similar
This way, you write less code, and you are flexible in the output format. Who knows if you want you complex number formatted differently next time? But this is another discussion.
Why complicating that much? Because C++ can be awfully complicated. It it very powerfull, but crammed with special syntax and exceptions to those. In the end, the difference to C lies exactly here: C++ does a much better job with type inference (needed for templates), often resulting in WTF?
On how to implement it in your code, i think the other answers provide nice solutions!
sumit(a) returns an object of type Complex, which cout was not defined to handle.