我不明白为什么不允许在非成员函数中使用诸如const
或volatile
之类的修饰符。
以下是我尝试过的示例代码:
class A
{
private:
int var;
public:
int func();
};
int A::func()
{
// Some calculation on using var
int temp = var + 10;
return temp;
}
void func2( const A& tempObj ) const;
void func2( const A& tempObj )
{
std::cout << "temp obj called : " << tempObj.func() << std::endl;
}
int main()
{
A aobj;
aobj.func();
func2( aobj );
return 0;
}
这会导致编译器错误 error C2270: 'func2' : modifiers not allowed on nonmember functions
,针对的是void func2( const A& tempObj ) const;
我还遇到了另一个错误 error C2662: 'A::func' : cannot convert 'this' pointer from 'const A' to 'A &'
,出现在 func2
中的 tempObj.func()
,我原本以为会无误地调用成员函数 func
。
无法将'this'指针从'const A'转换为'A&'
。我认为这里的转换是相反的。 - Krishna Ozaconst
限定符会有什么意义? - Angew is no longer proud of SOconst A&
中const
的目的。 - Angew is no longer proud of SO