Hi dear people i'm a new learning guy i come from a scripting language where no type was needed, after some day i think to know and appreciate that natural workflow. i have a few qustion about class...
if i made a class Myint
how can i make my class to return an integer type itself?
how the std::string class work's in that manner?
1 2 3 4
std::string im;
im = "some text"
std::cout << im //how can im be returned as *((char*)im)
#include <iostream>
class Myint{
public:
int me;
voidoperator = (constint &input){
me = input;
}
};
int main(void){
Myint oo;
oo = 10;
std::cout << oo; // cout threat oo as int
//or
int reali;
reali = oo; //oo returned from Myint class as integer type
return 0;
}
a = b; says that the equality operator returns a value which is assigned into a. A void = operator couldn't do that.
You can actually invoke these functions like normal functions via a class::operator = (arg) call.
The difference is simply how the value is returned and what is done with it. Calling =(b) with &(b) means b would be modified by its own value, and a would remain untouched. It doesn't work that way. For a = b, the argument to the = operator is b, not a.
a = b; says that the equality operator returns a value which is assigned into a.
No, the assignment operator is responsible for doing the assignment -- by modifying *this as necessary. The return value doesn't have anything to do with it.
Why should I use T& operator=(U input);
instead of voidoperator=(U const& input);
The short answer is to support code like
1 2 3 4 5
void modify(T& foo)
{ foo.change_me(); }
...
T t; U u;
modify(t = u);
Why should I use T& operator=(U input);
instead of voidoperator=(U const& input);
Another reason: it lets you say
1 2
Myint a,b;
a = b = 4;
Now granted, this construction and mobzzi's modify(t = u) are kind of rare, but they happen, and returning the reference is a small price to pay for the added flexibility. If the assignment operator is inlined, then the optimizer can tell whether the return value is used and remove the code that returns it when appropriate.