how do u overload operator << so that cout<<A prints out the letter A as well as the value of A

B

bluekite2000

Here A is an instantiation of class Matrix. This means whenever user
writes
Matrix<float> A=rand<float>(3,2);//create a float matrix of size 3x2
//and fills it up w/ random value
cout<<A;

the following will be printed
A
3
2
..1 .9
..2 .4
..5 .6

currently i only have
3
2
..1 .9
..2 .4
..5 .6

so I d like to add the string A.
 
V

Victor Bazarov

Here A is an instantiation of class Matrix. This means whenever user
writes
Matrix<float> A=rand<float>(3,2);//create a float matrix of size 3x2
//and fills it up w/ random value
cout<<A;

cout << "A\n" << A;
the following will be printed
A
3
2
.1 .9
.2 .4
.5 .6

currently i only have
3
2
.1 .9
.2 .4
.5 .6

so I d like to add the string A.

V
 
J

Jordan

If you wrote the Matrix class yourself, you are going to have to give
it a "name" member variable and name it in the constructor. Then you
merely pull out this value when you use "<<". I'm not sure you can
just reference the code name of a variable at runtime since it gets
compiled into machine code and no longer your naming scheme.
 
G

Guest

What you need is a meta-information "var-name", asking the var itself.
That's possible in Java or .NET, but not standardized in C++.

Workaround:
A simple approach would be

#define COUT_W_VARNAME(var) cout << #var << var
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

Here A is an instantiation of class Matrix. This means whenever user
writes
Matrix<float> A=rand<float>(3,2);//create a float matrix of size 3x2
//and fills it up w/ random value
cout<<A;

the following will be printed
A
3
2
.1 .9
.2 .4
.5 .6

If all you need is any identification on the output, you can use the address
of the object in operator<<:

#include <iostream>

using namespace std;

class Foo
{
friend ostream & operator<< (ostream &, Foo const &);

int i_;

public:

explicit Foo(int i)
:
i_(i)
{}
};

ostream & operator<< (ostream & os, Foo const & object)
{
return os << "Foo at " << &object << ":\n"
<< object.i_;
}

int main()
{
Foo object(42);
cout << object << '\n';
}

Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top