overload of operator=

P

paolo.dx

Hi, I have to overload operator= to call a method of a class, this is
what I need.

template<class I>
class port{
I dato;

public:
void write(I new_dato){
dato = new_dato;
};

I read(){
return(dato);
};

void operator= (I dato){
this->write(dato);
};
};

int main(){

int k,j;
port<int> my_port;

k=5;
my_port = k;
j = my_port; //i need to overload operator= to do my_port.read();

};

obviously I can call my_port.read() and my_port.write(k) but also I
have to be able to use the operator =
The overload for .write() is not a problem because the left side object
is an instance of class port, but how can I do for the .read()?
The operator= have to call the method .read() of the right side object,
and the left side is a standard type of c++.

Thanks in advance.
 
V

Victor Bazarov

Hi, I have to overload operator= to call a method of a class, this is
what I need.

template<class I>
class port{
I dato;

public:
void write(I new_dato){
dato = new_dato;
};

I read(){
return(dato);
};

void operator= (I dato){
this->write(dato);
};
};

int main(){

int k,j;
port<int> my_port;

k=5;
my_port = k;
j = my_port; //i need to overload operator= to do my_port.read();

};

obviously I can call my_port.read() and my_port.write(k) but also I
have to be able to use the operator =
The overload for .write() is not a problem because the left side
object is an instance of class port, but how can I do for the .read()?
The operator= have to call the method .read() of the right side
object, and the left side is a standard type of c++.

You cannot overload assignment to any built-in types. Your best solution
would be to provide the conversion function in your class template, which
will return a value of the type 'I':

template<class I> class port {
...
operator I() const { return dato; }
};

The compiler will pick this conversion where you give 'port<X>' and it
expects an 'X'.

V
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top