简体   繁体   中英

Cast char* to my string implicitly

I have my own string class ( DinString ), nothing special. I was wondering is possible to do something like this

DinString a= "Helo World";

bool Func(DinString string);

Func("test");

Yes, it is. Simply implement an appropriate (non- explicit !) constructor:

class DinString {
public:
    DinString( const char *s ) {
        // ...
    }
};

Please note that this won't work if you 'chain' more than one constructor like this. For instance, the following does not work :

class DinString {
public:
    DinString( const char *s ) {
        // ...
    }
};

class FooString {
public:
    FooString( const DinString & ) { }
};

void f( const FooString &) { }

f( "hello" ); // doesn't call FooString(DinString("hello!")); !

You can define a constructor to do this conversion for you:

class DinString {
  DinString(const char *string) { 
    // do something useful here
  }
};

This works because DinString a= "Helo World"; is not an assignment (despite appearances) and is actually equivalent to writing DinString a("Hello World");

是的,为您的类提供一个转换构造函数,将const char *作为输入。

DinString::DinString(const char *);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM