【问题标题】:Why const function can use a static member object's non-const function?为什么 const 函数可以使用静态成员对象的非常量函数?
【发布时间】:2020-12-23 03:49:12
【问题描述】:

代码1:

#include <iostream>
using namespace std;

class Test1 {
public:
  Test1() { num_ = 10; }
  int GetNum() { return num_; }

private:
  int num_;
};

class Test2 {
public:
  int GetNum() const { return t1_.GetNum(); }

private:
  static Test1 t1_;
};

Test1 Test2::t1_;

int main(int argc, char *argv[]) {
  Test2 t2;
  cout << t2.GetNum() << endl;
}

代码2:

#include <iostream>
using namespace std;

class Test1 {
public:
  Test1() { num_ = 10; }
  int GetNum() { return num_; }

private:
  int num_;
};

class Test2 {
public:
  int GetNum() const { return t1_.GetNum(); }

private:
  Test1 t1_;
};

int main(int argc, char *argv[]) {
  Test2 t2;
  cout << t2.GetNum() << endl;
}

两个代码的区别在于code1的t1_是静态的。 Code1 有效。但是 Code2 报错:

错误:将“const Test1”作为“int Test1::GetNum()”的“this”参数传递会丢弃限定符 [-fpermissive] int GetNum() const { return t1_.GetNum(); }

为什么 Code1 可以工作?

【问题讨论】:

    标签: c++


    【解决方案1】:

    作为非静态数据成员,t1_ 在 const 成员函数中相应地变为 const。然后t1_.GetNum() 导致错误,因为无法在 const 对象上调用非常量成员函数。

    另一方面,静态数据成员不属于对象;它不会因为在 const 成员函数中而成为 const。

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多