如何在GCC编译中修复const char*构造函数转换链错误

pet*_*erk 0 c++ gcc compiler-errors compilation

如果我尝试使用iOS4 sdk版本的gcc编译以下内容.
它给了我错误:

请求从'const char [4]'转换为非标量类型'UsesStr'

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";
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子,它是一个问题,当strptr是一个字符串类而不是使用但错误是相同的.


根据下面的答案,我尝试了这似乎工作.希望有一个"通用"字符串arg,它将接受许多类型的字符串,因为它将转换放在构造函数中以分解所有转换,而不需要在仅使用一种类型的事物中完全声明所有可能的字符串类型.

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;
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 7

static UsesStr ustr = "xxx";
Run Code Online (Sandbox Code Playgroud)

需要两个隐式转换,第一个来自const char[4]to strptr,第二个来自strptrto UsesStr.您不能连续两次隐式用户转换.这些将起作用:

static UsesStr ustr = strptr( "xxx" );
static UsesStr ustr = UsesStr( "xxx" );
static UsesStr ustr( "xxx" );
Run Code Online (Sandbox Code Playgroud)

如果您确实需要编写代码,那么您需要添加UsesStr一个构造函数strptr.