-4

在类构造函数中,我正在创建一个字符串并希望将其存储到*this. 构造函数中的这段代码不起作用:

// Inside the class constructor
string str1 = "hello";
*this = str1;

我应该使用其他数据类型来代替string str1吗?有什么建议么?

4

2 回答 2

1

很高兴看到你的班级定义,但鉴于它不存在,让我做一个长镜头并尝试猜测问题所在。

当你声明一个类时,它最初是空的。您不能在构造函数中存储任何内容。

class Empty {
   Empty() { /* can't do much here */ }
}

类由成员字段组成,这些字段可以为您存储数据。您可能想要做的是这样的事情:

class String {
    std::string member;
    String() {
        std::string str1 = "hello";
        member = str1;
    }
}
于 2012-11-30T23:05:53.793 回答
0

*this它是您的类对象的实例。

你不能做*this= str1;,直到你的课不是std::string

于 2012-11-30T23:01:03.547 回答