2016-06-21 2 views
-3
#include<vector> 
using namespace std; 

class Foo 
{ 
    private: 
    vector<int> m_vec; 
    public: 
    vector<int> getFoo() 
    { 
     return m_vec; // returns a copy of m_vec 
    } 
    vector<int>& getFooRef() 
    { 
     return m_vec; // returns a reference of m_vec 
    } 
}; 

int main() 
{ 
    Foo foo; 
    vector<int> x = foo.getFoo(); // init x with a copy of m_vec 
    vector<int>& y = foo.getFooRef(); // y is a reference to foo.m_vec - no new copy is created 
    vector<int> z = foo.getFooRef(); // what happens here?? Is the copy constructor invoked? 
    vector<int>& a = foo.getFoo(); // what happens here?? Is `a` a reference to a copy of m_vec? 
    return 0; 
} 
+1

[C++のポインタ変数と参照変数の違いは何ですか?](http://stackoverflow.com/questions/57483/what-are-the-datferences-between-a-pointer- variable-and-a-reference-variable-in) – tkausl

+0

'z'は参照自体ではないので、' m_vec'のコピーで初期化されます。メソッドから 'm_vec'への参照が返されますが、' z'に代入すると[コピー代入演算子](http://en.cppreference.com/w/cpp/language/copy_assignment)が実行されます。ありがとう。 – Jezor

+0

ありがとう。それは私の質問に答える – arunmoezhi

答えて

3

に変数を初期化するためにどういう意味は、変数の初期化を実行するために=演算子の右側の参照を使用しています=オペレータの左側にあるz

実際の初期化の動作の性質は、左側、つまりzによって決まります。 zではないので、参照番号の参照番号=は、参照によって得られたベクトルの内容をzにコピーします。

関連する問題

 関連する問題