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