这是我的代码:
class X
{
public:
X():_x(5){}
void GetVal(int & oVal)
{
oVal = _x;
}
private:
int _x;
};
class Y
{
public:
X * const GetX()
{
return &_x;
}
private:
X _x;
};
int main()
{
Y y;
X * p = y.GetX();
int * pInt = new int[2];
p->GetVal(pInt[0]);
}
在main的最后一行,我得到一个错误
Incorrect access of a member from const-qualified function
这个错误只有在sun solaris系统上编译时才会出现,在windows或aix系统上不会出现。知道为什么吗?
同样最奇怪的是,如果我用一个简单的整数 (int a = 0; p->GetVal(a)) 替换 pInt[0],错误就消失了
最佳答案
X * const GetX()
中的const
会被忽略,因为函数调用的结果是右值,非类类型的右值不能是const
根据 c++ const member function that returns a const pointer.. But what type of const is the returned pointer? .
你确定你不是故意写的吗:
const X * GetX() const
{
return &_x;
}
也就是你把它从返回一个指向变量date的常量指针变成了一个指向常量数据的变量指针,你把GetX()
声明为一个常量成员函数,也就是一个成员函数可用于 Y 的常量实例:const Y y;
此外,在 class X
中,您可以将 GetVal()
更改为
void GetVal(int & oVal) const
{
oVal = _x;
}
关于c++ - 编译 C++ 代码时在 sun 操作系统上出现 "const access error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13117639/