0
我对C++中引用感到困惑。任何人都可以解释我这样的:引用变量
class Dog
{
public:
Dog(void) {
age = 3;
name = "dummy";
}
void setAge(const int & a) {
age = a;
}
string & getName(void) {
return name;
}
void print(void) {
cout << name << endl;
}
private:
int age;
string name;
};
int main(void) {
Dog d;
string & name = d.getName(); // this works and I return reference, so the address of name will be the same as address of name in Dog class.
int a = 5;
int & b = a; // why this works? by the logic from before this should not work but the code below should.
int & c = &a // why this does not work but the code above works?
}
还当我删除&
,使这样的string getName
函数的代码将无法正常工作。
*这个作品和我回来参考,所以姓名的地址将与Dog类中的姓名地址相同*不可以。不要将引用视为指针。他们可以像他们一样行事,并与他们一起实施,但他们不是指针。他们是参考。 – NathanOliver
一些很好的阅读:https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – NathanOliver
我没有说他们是指针但两个变量的地址是相同的,它不像来自主函数的变量名具有值,它是来自Dog类的变量名的地址。 – stilltryingbutstillsofar