考虑以下代码:

class Bar
{
public:
    int GetValue() const { return aVeryImportantValue; }
    void SetValue(int value) { aVeryImportantValue = value; }

private:
    int aVeryImportantValue;
};

class Foo
{
public:
    Foo(const Bar &bar) : _bar(bar) {}

    void SetBar(const Bar &bar) { _bar = bar; }//my compiler won't like this
    int GetValue() const { return _bar.GetValue(); }

private:
    const Bar &_bar;
};

如果我希望能够通过Foo“检查”不同的Bar对象,又要确保Foo实际上不会更改Bar的内容怎么办?可能吗?

最佳答案

您可以使用指向常量对象的指针:

const Bar *_bar;

您可以切换一个指针变量,并确保Foo不会更改其状态。
class Foo
{
public:
    Foo(const Bar *bar) : _bar(bar) {}
    void SetBar(const Bar *other) { _bar = other; }
    int GetValue() const { return _bar->GetValue(); }

private:
    const Bar *_bar;
};

09-10 03:28
查看更多