我怎样才能让这个函数像左值一样?
为什么我不能使用函数 ColPeekHeight()
作为左值?
class View
{
public:
int ColPeekHeight(){ return _colPeekFaceUpHeight; }
void ColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
if( v.ColPeekHeight() > 0.04*_heightTable )
v.ColPeekHeight()-=peek;
}
编译器在 v.ColPeekHeight()-=peek
处进行抱怨。如何使 ColPeekHeight()
成为左值?
Why can't I use the function ColPeekHeight()
as an l-value?
class View
{
public:
int ColPeekHeight(){ return _colPeekFaceUpHeight; }
void ColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
if( v.ColPeekHeight() > 0.04*_heightTable )
v.ColPeekHeight()-=peek;
}
The compiler complains at v.ColPeekHeight()-=peek
. How can I make ColPeekHeight()
an l-value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过引用返回成员变量:
为了使您的类成为一个好的类,请定义该函数的 const 版本:
当您想要将对象传递给函数时,您不希望它修改您的对象。举个例子:
如果您将对象传递给函数,那么您可能不想一直更改它们。因此,为了防止这种更改,您可以声明成员函数的 const 版本。不一定每个成员函数都有两个版本!这取决于函数本身,它本质上是否修改函数:)
第一个
const
表示返回值是常量。第二个const
表示成员函数return_x
不会更改对象(只读)。Return the member variable by reference:
To make your class a good one, define a const version of the function:
When you want to pass an object into a function that you don't expect it to modify your object. Take this example:
If you pass your objects to functions, then you might not want to change them actually all the time. So, to guard your self against this kind of change, you declare
const
version of your member functions. It doesn't have to be that every member function has two versions! It depends on the function it self, is it modifying function by nature :)The first
const
says that the returned value is constant. The secondconst
says that the member functionreturn_x
doesn't change the object(read only).它可以重写为:
It can be rewritten like: