C++常量参数指令阻止类的函数使用

C++ const parameter directive blocks function use of class

本文关键字:函数 常量 参数 指令 C++      更新时间:2024-09-27

我有一个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;
}
};