为什么我可以在const成员函数中调用成员的非常量函数?

问题描述 投票:0回答:1

当我使用 VisualStudio 2015 编译以下代码时,仅在

GetValueUsingObject()
成员函数上出现 C2662 编译器错误。

代码:

class Member
{
public:
    int GetValue() { _value = 1; return _value; }

private:
    int _value;
};

class Test
{
public:
    Test() : _pointer(new Member()) {}
    int GetValueUsingPointer() const { return _pointer->GetValue(); } // Okay
    int GetValueUsingObject() const { return _object.GetValue(); }    // C2662 Error

private:
    Member* _pointer;
    Member _object;
};

编译错误信息:

C2662 'int Member::GetValue(void)':无法将 'this' 指针从 'const Member' 转换为 'Member &'

我认为

GetValueUsingPointer()
GetValueUsingObject()
函数都违反了常量性。但是,
GetValueUsingPointer()
没有编译问题。

为什么可以?

c++ visual-studio constants
1个回答
0
投票

您没有调用成员函数。您使用成员指针(即

const
),取消引用它,然后调用指针指向的对象的成员函数。而那个物体不是
const

如果指针让您感到困惑,请考虑一个示例,其中您有一个索引到全局数组的成员:

std::array<int,42> memory;

struct foo {
    size_t index = 23;
    void bar() const {
        memory[index] = 0;  // does not modify index
    }
};

A

const foo
有一个常量
index
,但您可以使用该
index
来访问
index
中的第
memory
元素并修改它:

您可以将指针想象为

memory
的索引。指针恒定并不意味着该内存中存储的内容是恒定的。你可以有一个指向常量对象的非常量指针,一个指向非常量对象的常量指针,等等。在常量
Test
中,成员
_pointer
是常量,它指向的对象不是常量。

© www.soinside.com 2019 - 2024. All rights reserved.