【发布时间】:2015-03-18 07:29:07
【问题描述】:
我不明白为什么不允许像 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;
}
对于void func2( const A& tempObj ) const; 会引发编译器错误error C2270: 'func2' : modifiers not allowed on nonmember functions
我还收到另一个错误error C2662: 'A::func' : cannot convert 'this' pointer from 'const A' to 'A &' for tempObj.func() in func2 在这里我假设成员函数 func 将被调用而没有任何错误。
【问题讨论】:
-
也请帮助他理解
cannot convert 'this' pointer from 'const A' to 'A &'。我认为这里的转换正在以其他方式发生。 -
我在您的示例中没有看到 volatile 关键字?
-
你能解释一下你认为修饰符是什么意思吗?
-
我确实检查了更新,您只是添加了另一个问题,但没有回答我的问题。您认为非成员函数上的
const限定符的含义是什么? -
@Krishna_Oza 这就是
const A&中const的目的。