c++ - 编译 C++ 代码时在 sun 操作系统上出现 "const access error"

标签 c++ unix compiler-errors solaris

这是我的代码:

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/

相关文章:

c++ - 从另一个进程中查找变量的地址

linux - 在其他脚本成功执行后执行 Shell 脚本

c - 为什么 Clang 会看到类型冲突?

sockets - getsockopt 中的参数级别是什么?

java - 更新 2D Java 数组中的对象

C编程,错误: called object is not a function or function pointer

c++ - 在构造函数中传递和存储静态函数指针

c++ - 大文本显得模糊

c++ - 为 win32 线程使用不同的静态库内存

regex - 创建条件 bash 脚本代码