How do I fix a const char * constructor conversion

2019-09-02 19:01发布

问题:

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;

回答1:

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.



回答2:

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.