【发布时间】: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++