【问题标题】:How do I fix a const char * constructor conversion chain error in GCC compile如何修复 GCC 编译中的 const char * 构造函数转换链错误
【发布时间】:2011-10-12 03:56:51
【问题描述】:

如果我尝试使用 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";

这是一个简单的例子,问题是当 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;

【问题讨论】:

    标签: c++ gcc compilation compiler-errors


    【解决方案1】:
    static UsesStr ustr = "xxx";
    

    需要两次隐式转换,第一次从const char[4] 到strptr,第二次从strptr 到UsesStr。您不能连续进行两次隐式用户转换。这些会起作用:

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

    如果您确实需要编写代码,那么您需要在UsesStr 中添加来自strptr 的构造函数。

    【讨论】:

    • 上面的代码没有来自 strptr 的构造函数吗?或者你的意思是不是一个 const & 到 strptr ?谢谢。
    【解决方案2】:

    使用这个:

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

    我不认为编译器可以处理隐式转换链:在您的情况下,从 const char* 到 strptr 到 UsesStr。

    【讨论】:

    • 唉 - MSC 做到了,较新的 GCC 没有。因此,不能为方法或构造函数提供“变体”参数并使其在两者上都起作用。
    • BTW MSC 可以设置为执行所有这些操作,因为它的重载解决优先级与 GCC 不同,它按来自源的跳数(GCC)进行优先级排序 - 我似乎是最新的如果有另一个隐式链导致显式构造函数的值和其他一些东西,则忽略“显式” - 结果是很难手动控制构造函数重载优先级。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多