0

私は小さな C++ プログラムを構築しており、クラスにカスタム演算子を実装しています。また、私は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
  }
4

1 に答える 1

0

をしている場合は、(公開さ~A = dれている場合) と同じです。A.v = dv

古いオブジェクトvを新しいオブジェクトに交換するのではなく、 の内容を の内容のコピーにd置き換えるだけです。詳細については、 を参照してください。A.vdvector::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();
}

これは期待どおりに出力されます(ここでわかるように):

Hello
world
于 2013-05-22T09:13:26.887 に答える