2017-07-06 68 views
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函數的代碼將無法正常工作。

+0

*這個作品和我回來參考,所以姓名的地址將與Dog類中的姓名地址相同*不可以。不要將引用視爲指針。他們可以像他們一樣行事,並與他們一起實施,但他們不是指針。他們是參考。 – NathanOliver

+0

一些很好的閱讀:https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – NathanOliver

+0

我沒有說他們是指針但兩個變量的地址是相同的,它不像來自主函數的變量名具有值,它是來自Dog類的變量名的地址。 – stilltryingbutstillsofar

回答

2

萬一

int & b = a; 

b是由兩個名字ab參照a和存儲器分配用於類型的數據int是可用的。

如果

int & c = &a; 

你要保存的分配a內存地址 - 一元的結果& - 以int & c ...這導致錯誤。

在方法的情況下

string & getName(void) 

參照string返回,所以string & name(在main變量)將提供訪問私有類成員的存儲器string name;