开发者

How can I make this function act like an l-value?

开发者 https://www.devze.com 2022-12-23 21:21 出处:网络
Why can\'t I use the function ColPeekHeight() as an l-value? class View { public: int ColPeekHeight(){ return _colPeekFaceUpHeight; }

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开发者_Go百科 l-value?


Return the member variable by reference:

int& ColPeekHeight(){ return _colPeekFaceUpHeight; }

To make your class a good one, define a const version of the function:

const int& ColPeekHeight() const { return _colPeekFaceUpHeight; }

when I declare the function with the two consts

When you want to pass an object into a function that you don't expect it to modify your object. Take this example:

struct myclass
{
    int x;
    int& return_x() { return x; }
    const int& return_x() const { return x; }
};
void fun(const myclass& obj);

int main()
{
    myclass o;
    o.return_x() = 5;
    fun(o);
}
void fun(const myclass& obj)
{
    obj.return_x() = 5; // compile-error, a const object can't be modified
    std::cout << obj.return_x(); // OK, No one is trying to modify obj
}

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 second const says that the member function return_x doesn't change the object(read only).


It can be rewritten like:

class View
{
    public:
        int  GetColPeekHeight() const  { return _colPeekFaceUpHeight; }
        void SetColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
    private:
        int _colPeekFaceUpHeight;
};

...

{
    cph = v.GetColPeekHeight();
    if ( cph > 0.04 * _heightTable )
        v.SetColPeekHeight( cph - peek );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号