我的代码是这样的
std::string & Product::getDescription() const {
return &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&}"的引用无效
初始化引用时&
不要对变量使用运算符:
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;
}
返回引用时,不使用 address-of
运算符:
class Product
{
std::string description;
const std::string& get_description() const { return description; }
void set_description(const std::string& desc) { description = desc; }
};
这是一个const
成员函数,这意味着调用它的对象(及其成员)const
在函数中。不能返回对成员的非常量引用。
您可以从const
函数返回const
引用:
const std::string & Product::getDescription() const;
以及来自非常量函数的非常量引用
std::string & Product::getDescription();
假设description
的类型为 std::string
,您将只返回 return description;
的引用,没有&
。
set
函数不能const
,因为它修改了对象。
你的方法Product::getDescription() const
应该返回对 const 对象的引用,因为该方法是 const 的。更重要的是,&description
是指向字符串的指针,因为在该上下文中&
是 address-of 运算符。不要从指针初始化引用。使用以下内容:
const std::string & Product::getDescription() const { return description; }