c++ - Overloading assignment operator: different datatypes - impossible? -
i trying make impossible operator overloading. particularly interested in overloading assignment operator, receive another data type value right hand value. should this:
myclass myclass = "hello world"; <--- wrong? myclass myclass2; myclass myclass = myclass2; <--- right?
then myclass
object should receive string , handle it. unfortunately, read possible assign same data type value custom made class. true or mistaken?
this code have:
class myclass { public: myclass() {}; virtual ~myclass(); myclass& operator = (const myclass&); private: char* string; }; myclass& myclass::operator= (const myclass& inc){ string = inc; } int main(int argc, char** argv) { myclass myclass = "hello world"; std::cout << myclass; }
as can see, want cout
object string. basically, want custom class treated string. search in google , stackoverflow search engines denied wish, or there workaround?
looking forward hear , thank in advance!
edit: rollie fixed main problem. however, how cout
string value of custom object myclass
? possible, since object output memory address of object being outputted?
myclass myclass = "hello world";
not assignment - it's constructor, , logically equivilent myclass myclass("hello world");
. overload both constructor , assignment operators, , you'll have behavior looking for!
also comments:
1) isn't great idea name member variable string
- name of common stl type
2) setting variable directly time bomb; aren't copying value of string, copying pointer. switch std::string
copies happen automatically
3) cout
work properly, see answer @ stackoverflow.com/questions/5508857/how-does-cout-actually-work
Comments
Post a Comment