【问题标题】:C++ what's difference of param with const and without const in class constructor [duplicate]C ++类构造函数中带有const和不带const的param有什么区别[重复]
【发布时间】:2020-09-02 12:50:59
【问题描述】:

我有这段代码,但编译失败:

class TextBlock
{
    public:
        TextBlock(std::string &s)
        {
            text = s;
        }

    private:
        std::string text;
};
int main()
{
    TextBlock tb("Hello");
    std::cout<< tb[0] << std::endl ;
}

为什么构造函数为TextBlock(const std::string &amp;s)时上面的代码可以编译成功?

【问题讨论】:

  • 临时不能绑定到非常量(左值)引用。
  • 草率地说你需要一个字符串,引用只是一个引用。如果引用是const,那么该函数可以使用临时函数,因为无论如何它都不会被修改。将临时值传递给需要非常量引用的函数是没有意义的,因为您无法观察到修改,因此这是一个错误是有道理的

标签: c++ constructor


【解决方案1】:

构造函数正在指定一个对字符串的引用:

std::string  x{"hello"};
TextBlock tb(x);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2011-10-19
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多