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

标签 c++ gcc compilation compiler-errors

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

最佳答案

static UsesStr ustr = "xxx";

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

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

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

关于c++ - 如何修复 GCC 编译中的 const char * 构造函数转换链错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735107/

相关文章:

vba - "compile project"在 Word 2010 VBA 编辑器中不可用

c++ - 测试目录中的另一个 main.cpp

c++ - 强制或阻止使用特定次要版本的 libstdc++

linux - 构建 Linux 内核时通过 -S 选项生成汇编文件

c++ - 初始化列表中 const 引用成员的初始化

gcc - 奇怪的编译错误

android - 从 Android Rom 中完全删除 WiFi(包括设置布局)

C++ 在 MPI 进程之间共享大型数组和数据结构

c++ - QTextDocument、QPdfWriter - 如何缩放输出

c++ - 如何处理 C++ 中的构造函数失败?