c++ - Overloading operator= or operator[] using const char* and/or string -


i've been scouring google , stackoverflow so-far no clear answer this, i'm asking directly...

i made bitmap font class , i'd use assignment operator: operator=(const char*) assign string literal text of class. note: i'd assign using string, string* , char*... example:

class bitmaptext{ private:     std::string _text; public:     void operator=(const char* _t){         _text = _t;     }     /*i've tried iteration of operator using     bitmaptext& operator=(const char* _t){         _text = _t;         return *this;     }     */     bitmaptext(){}     ~bitmaptext(){} };   bitmaptext* t1 = new bitmaptext(); t1 = "hello world" 

assigning char string bitmaptext object yields following:

assigning 'bitmaptext*' 'const char[12]' incompatible type. 

i'm sure there's reason this. can done string class. looked string class , typedef'd from:

typedef basic_string<char, char_traits<char>, allocator<char> > string; 

is why can assign char array string class? because somehow seems inherit characteristics of char? can overload way i'm trying without such complicated implementation?

my second question (i think) along same lines: want use operator[](const char* _name) return child object who's name matches _name value.

every operator overloading example @ uses right-hand operands of same class type 1 being overloaded. have read however, can use different data types, , can use char* assign value std::string object...

what missing? , appreciated.

define operator following way

bitmaptext & operator =( const std::string &t ) {     _text = t;      return *this; } 

it can used objects of type std::string , objects of type char * because there implicit conversion const char * std::string due conversion constructor of class std::string.

as code snippet

bitmaptext* t1 = new bitmaptext(); t1 = "hello world" ^^^               ^^ 

then has rewritten following way

bitmaptext* t1 = new bitmaptext(); *t1 = "hello world"; 

this statement

t1 = "hello world"; 

is wrong because trying assign pointer of type const char * pointer of type bitmaptext *.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -