使用const char *和/或string

时间:2015-07-21 21:19:22

标签: c++ string char operator-overloading

我一直在搜索谷歌和stackoverflow迄今为止没有明确的答案,所以我直接问...

我创建了一个位图字体类,我想使用赋值运算符:operator =(const char *)将字符串文字分配给类的文本。 注意:我还想使用string,string *和char *来分配... 例如:

class BitmapText{
private:
    std::string _text;
public:
    void operator=(const char* _t){
        _text = _t;
    }
    /*I've also tried another iteration of this operator using
    BitmapText& operator=(const char* _t){
        _text = _t;
        return *this;
    }
    */
    BitmapText(){}
    ~BitmapText(){}
};


BitmapText* t1 = new BitmapText();
t1 = "Hello World"

将char字符串分配给BitmapText对象会产生如下内容:

Assigning to 'BitmapText*' from 'const char[12]' incompatible type.

我确信这是有充分理由的。但它可以用字符串类来完成。我查看了字符串类,它是来自:

的typedef
typedef basic_string<char, char_traits<char>, allocator<char> > string;

这就是为什么我可以为字符串类分配一个char数组?因为它似乎在某种程度上继承了char的特征?如果没有这么复杂的实现,我可以重载我正在尝试的方式吗?

我的第二个问题是(我认为)沿着同样的路线: 我想使用operator [](const char * _name)返回名称与_name值匹配的子对象。

我看到的每个运算符重载示例都使用与正在重载的类操作数相同的类操作数。不过我读过,你可以使用不同的数据类型,我们可以清楚地使用char *为std :: string对象赋值...

我错过了什么? 任何和所有的帮助都非常感激。

3 个答案:

答案 0 :(得分:4)

您尝试分配给t1BitmapText不是BitmapText,而是指向*t1 = "Hello World";的指针;

如果你做set -e它应该有效。

答案 1 :(得分:4)

按以下方式定义运算符

BitmapText & operator =( const std::string &t )
{
    _text = t;

    return *this;
}

它可以用于类型为std::string的对象和类型为char *的对象,因为由于类的转换构造函数而存在从const char *std::string的隐式转换std::string

至于此代码段

BitmapText* t1 = new BitmapText();
t1 = "Hello World"
^^^               ^^

然后必须按以下方式重写

BitmapText* t1 = new BitmapText();
*t1 = "Hello World";

本声明

t1 = "Hello World";

是错误的,因为您尝试将类型为const char *的指针分配给BitmapText *类型的指针。

答案 2 :(得分:0)

您正在尝试分配指针,即字符串文字的地址。 而是尝试:

BitmapText* t1 = new BitmapText();
(*t1)= "Hello World";
相关问题