【问题标题】:What does invalid initialization of reference mean?引用的无效初始化是什么意思?
【发布时间】:2014-03-23 04:29:58
【问题描述】:

我的代码是这样的

std::string & Product::getDescription() const { return &description; }

我已经用 description 和 *description 尝试了所有不同的方法,但没有任何效果,但是当我去掉返回类型的引用部分时,它工作正常。问题是我们应该使用 &。我真的很困惑为什么没有任何效果。在项目的早期还有代码:

void Product::setDescription(const std::string &newUnits) const { units = newUnits; }

单位被声明为全局公共变量。它给我的确切错误是:

错误:从“const string {aka const std::basic_string}”类型的表达式中对“std::string& {aka std::basic_string&}”类型的引用进行无效初始化

【问题讨论】:

  • description是什么类型?
  • 你确定这是正确的错误信息吗?
  • 能否提供Product的完整声明?
  • 您声明返回一个引用,但您返回的是一个指针(&description 是一个地址)

标签: c++ reference compiler-errors initialization


【解决方案1】:

当您初始化引用时,您不会在变量上使用& 运算符:

int i = 0;
int& j = i;  // now j is reference for i

同样在函数中,返回不带&的变量:

std::string& Product::getDescription() const {
    return description;
} // equivalent for std::string& returned = description;

此外,您只能从 const 函数返回 const 引用。所以应该是:

const std::string& Product::getDescription() const {
    return description;
}

std::string& Product::getDescription() {
    return description;
}

【讨论】:

  • 谢谢!我在发布这篇文章大约十分钟后弄清楚了我做了什么,但解释总是很受欢迎!
【解决方案2】:

您的方法Product::getDescription() const 应该返回一个对 const 对象的引用,因为该方法是 const。更重要的是,&description 是指向字符串的指针,因为在该上下文中,&address-of 运算符。您不会从指针初始化引用。使用以下内容:

const std::string & Product::getDescription() const { return description; }

【讨论】:

    【解决方案3】:

    这是一个const 成员函数,这意味着调用它的对象(及其成员)是函数内的const。您不能返回对成员的非常量引用。

    您可以从 const 函数返回 const 引用:

    const std::string & Product::getDescription() const;
    

    以及来自非常量函数的非常量引用

    std::string & Product::getDescription();
    

    假设description 的类型为std::string,您将只返回带有return description; 的引用,而没有&

    set 函数不能是const,因为它修改了对象。

    【讨论】:

      【解决方案4】:

      返回引用时,您不使用address-of 运算符:

      class Product
      {
         std::string description;
         const std::string& get_description() const { return description; }
         void set_description(const std::string& desc) { description = desc; }
      };
      

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 2022-01-01
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        • 2020-07-17
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多