无效初始化参考意味着什么?

时间:2014-02-21 15:16:04

标签: c++ reference compiler-errors initialization

我的代码就像这样

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

我已经尝试了所有不同的方式与描述和*描述,没有任何作品,但当我取消返回类型的参考部分,它工作正常。事情是,我们应该使用&amp ;.我真的很困惑为什么没有任何作用。项目早期还有代码:

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

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

  

错误:'std :: string&类型的引用的初始化无效来自'const string {aka const std :: basic_string}'的表达式的{aka std :: basic_string&}'

4 个答案:

答案 0 :(得分:2)

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

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;
}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

这是一个const成员函数,意味着它被调用的对象(及其成员)在函数中是const。您不能将非const引用返回给成员。

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

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

和来自非const函数的非const引用

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

假设description的类型为std::string,您只需return description;即可返回引用,而不会&

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

答案 3 :(得分:0)

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

const std::string & Product::getDescription() const { return description; }
相关问题