开发者

How do I fix a const char * constructor conversion chain error in GCC compile

开发者 https://www.devze.com 2023-04-12 04:22 出处:网络
If I try to compile the below with the iOS4 sdk version of gcc. 开发者_运维问答It gives me the error:

If I try to compile the below with the iOS4 sdk version of gcc.

开发者_运维问答It gives me the error:

Conversion from 'const char[4]' to non-scalar type 'UsesStr' requested

class strptr {
public:
    strptr(const char * s) : s_(s) {}
    const char *c_str() const { return(s_); }
protected:
    const char *s_;
};


class UsesStr {
public:
    UsesStr(const strptr &sp)
        : p_(sp.c_str())
    {
    }
    const char *p_;
};


static UsesStr ustr = "xxx";

This is a simple case, it is a problem is when strptr is a string class that is used instead but the error is the same.


based on answer below I tried this which does seem to work. Desire to have a "universal" string arg that will accept many types of strings as it puts the conversion in the constructor to factor out all the conversions and not require complete declarations of all the possible string types in things that use only one type.

class UsesStr;

class strptr {
public:
    strptr(const char * s) : s_(s) {}
    strptr(UsesStr &s);

    const char *c_str() const { return(s_); }
    operator const char *() const { return(s_); }

private:
    const char *s_;
};


class UsesStr {
public:
    template<typename arg>
    UsesStr(const arg &sp)
        : p_(strptr(sp).c_str())
    {}
    UsesStr(const strptr &sp) : p_(sp.c_str()) 
    {}
    const char *p_;
    operator const strptr() const { return(strptr(p_)); } 
};

strptr::strptr(UsesStr &s)
    : s_(s.p_) {}


static UsesStr ustr = "xxx";
static UsesStr ustr2 = ustr;
static strptr sp = ustr2;    
static UsesStr ustr3 = sp;


static UsesStr ustr = "xxx";

requires two implicit conversions, the first from const char[4] to strptr and the second from strptr to UsesStr. You can't have two implicit user convertions in a row. These would work:

static UsesStr ustr = strptr( "xxx" );
static UsesStr ustr = UsesStr( "xxx" );
static UsesStr ustr( "xxx" );

If you really need to have the code as you wrote it, then you will need to add in UsesStr a constructor from a strptr.


Use this :

static strptr sptr = "xxx";
static UsesStr ustr = sptr ;

I dont think the compiler can handle a chain of implicit conversions : in your case from const char* to strptr to UsesStr.

0

精彩评论

暂无评论...
验证码 换一张
取 消