【发布时间】:2020-08-16 21:19:38
【问题描述】:
我有个问题。我目前正在研究 C++ 中的一个小例子,但无法弄清楚解释。这是我的问题:
#include <iostream>
using namespace std;
class X{
int& i ; /* int i; */
public :
X(int k=100):i(k){ }
X(`const` X& x):i(x.i){}
void setI(int k){i=k;}
int getI(){cout <<"adresse: "<< &i << " Contenue: "<<i<<endl ; return i;}
};
int main(){
int i =7;
X a(i);
a.getI();
a.setI(5);
a.getI();
cout << "the value of i is: " << i << endl;
X b(a);
b.getI();
cout << "the value of i is: " << i << endl;
X c;
c.getI();
a.getI();
return 0;
}
所以我不明白的是为什么变量成员 i 在 X 类像类变量一样工作?我在网上搜索并发现 它被称为聚合并且出于某些原因而使用它,但是 我不明白为什么会这样?编译器是怎么做的 那个?
请您向我解释一下。
感谢上一页。
【问题讨论】:
-
为什么你认为
i表现得像一个类变量?你期望什么行为,你实际得到什么? -
创建多个实例后,我发现 i 引用了相同的变量
-
在这种情况下,声明它
static -
感谢您的建议,但我只想了解它的行为。
标签: c++ class reference class-variables member-variables