C++常量参数指令阻止类的函数使用
C++ const parameter directive blocks function use of class
我有一个C++类,它被用作函数参数,这让我有些悲伤。当函数被指定为const时,我似乎无法从类参数中调用它。
样品类别:
class FooBar
{
private:
bool barFoo; // I want this modifiable only through functions
public:
const bool& getBarFoo() // this function needs to be used to retrieve it
{
return barFoo;
}
void setBarFoo(bool newVal) // this is the set function. It validates if the set is possible
{
// check if modification is possible.
barFoo = newVal
}
}
我尝试在类似于以下的函数中使用这个类:
void DoShizzle(const FooBar& yesOrNo)
{
if(yesOrNo.getBarFoo()) // here the code shows an error*
{
// do shizzle
}
else
{
// do other shizzle
}
}
*消息说"对象具有与成员函数不兼容的类型限定符";FooBar::getBarFoo"对象类型为:const FooBar'。
如果我从DoHizzle函数中的FooBar参数中删除"const"指令,错误就会消失。然而,我读到你应该试着告诉开发人员和编译器你在做什么。我想将变量barFoo保持为私有,以便只能使用setBarFoooHizzle不会编辑FooBar类。
什么能很好地解决我的问题?接受我不能在这里使用const的事实吗?还是我错过了另一个解决问题的方法?我是C++的新手,也是一个天生的C#开发人员,所以我知道我可能不得不放弃一些实践
const
限定符与其返回类型的const
限定符不一定相同。实际上,它们通常是不相关的(只有当您返回对成员的引用时,从const
方法只能获得const
引用(。您的方法:
const bool& getBarFoo() // this function needs to be used to retrieve it
{
return barFoo;
}
是一个返回const bool&
(对bool
的常量引用(的非常量方法。
如果您希望能够在const FooBar
上调用该方法,则必须将该方法声明为const
:
const bool& getBarFoo() const // <--------
{
return barFoo;
}
问题是当前成员函数getBarFoo
不能用于FooBar
类型的const
对象。
要解决此问题,您应该通过添加const
使成员函数getBarFoo
成为常量成员函数,如下所示:
class FooBar
{
private:
bool barFoo;
public:
////////////////////////VVVVV
const bool& getBarFoo() const //added const here
{
return barFoo;
}
void setBarFoo(bool newVal)
{
barFoo = newVal;
}
};
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- constexpr构造函数需要常量成员函数时出现问题
- std::函数常量正确性未遵循
- 具有常量引用参数的函数模板专用化
- constexpr 函数获取常量字符*
- 在定义的函数中使用常量时出错
- Clang 格式 10.0 与 5.0 常量成员函数的格式不同
- C++ 获取函数在常量引用中按值返回的结果
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 为什么下面带有非常量转换函数的代码没有歧义?
- 与 map 一起使用时复制构造函数常量错误
- 静态函数常量静态成员函数
- 如何在指向常量地址时声明成员函数常量指针
- C++getter函数:常量和非常量
- C++循环中调用伪随机数生成器函数 - 常量种子问题
- 提升::任何构造函数 - 常量类型重载分辨率
- 函数常量返回类型:类型引用的初始化无效
- C++模板通过指针的函数/常量指针的函数进行的部分专用化没有什么不同
- 虚函数常量与虚函数非常量