2017-07-06 56 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;