2013-05-22 49 views
0

我正在構建一個小型C++程序,並且正在實現一個類中的自定義運算符。此外,我正在使用STL向量。返回對stl向量的引用

但是我被困在一開始。這是我的接口類:

class test { 

    vector<string> v; 
    public: 
     vector<string>& operator~();  
}; 

而這裏的實現:

vector< string>& test::operator~(){ 

    return v; 
} 

我想引用返回向量所以在主程序中,我可以做這樣的事情

int main(){ 

    test A; 
    vector<string> c; 
    c.push_back("test"); 
    ~A=c; 
//i want to do it so the vector inside the class takes the value test,thats why i need reference 

} 

更新

該程序起作用但它不返回對該類屬性的引用,例如:

如果我有這樣的事情:

int main(){ 

     test A; 
     A.v.push_back("bla"); 
     vector<string> c; 
     c=~A; 
     //This works, but if i want to change value of vector A to another vector declared in main 
     vector<string> d; 
     d.push_back("blabla"); 
     ~A=d; 
     //the value of the A.v is not changed! Thats why i need a reference to A.v 
    } 
+2

有什麼錯誤? – Blazes

+2

你真的需要這樣做嗎?這似乎是濫用'operator〜'。 – juanchopanza

+0

〜A = c; < - 這是如何工作的? – KillAWatt1705

回答

0

當你在做~A = d,這是一樣的A.v = d(如果v是公開的)。

它不會與新對象d換舊的對象v,它只會替換的A.v內容用的d內容的副本,請參閱more information about vector::operator=

class test { 
    vector<string> v; 
    public: 
    test() { 
     v.push_back("Hello"); 
    } 

    void print() { 
     for(vector<string>::iterator it=v.begin(); it!=v.end(); ++it) { 
      cout << *it; 
     } 
     cout << endl; 
    } 

    vector<string>& operator~() { 
     return v; 
    }  
}; 

int main(){ 
    test A; 
    A.print(); 
    vector<string> c; 
    c.push_back("world"); 
    ~A = c; 
    A.print(); 
} 

這個輸出如預期(因爲你可以看到here):

Hello 
world