2013-12-23 145 views
0

我想寫我自己的矢量類,使用重載進行某些操作,如輸入/輸出元素和push_back()運算符超載

我該如何重載加法運算符?現在,我把它cout數組的各個元素相加兩個向量中的每個元素之後,但我想這樣做: myVector c = vec + vec2

然後cout << c << endl

請問我需要寫我自己的副本構造函數?

myVector::myVector(myVector& v) 
{ 
    cout << "Copy constructor called." << endl; 
    this->array = new int[v.maxsize]; 
    this->array = v.array; 
    cout << "Returning from Copy constructor." << endl; 
} 

這是我的重載加法運算符:

myVector myVector::operator+(myVector& a) 
{ 
    cout << "Addition operator overloaded" << endl; 
    myVector result; 
    result.array = new int[a.maxsize]; 
    for (int i = 0; i < a.size(); i++) 
     result.array[i] = this->array[i] + a.array[i]; 
    result.setSize(a.size()); 
    return result; 

} 

下面是完整的源代碼: http://pastebin.com/raw.php?i=9nkWVLwy

+0

我創建了一個新的'myVector'對象並將其返回。但我得到一個運行時錯誤。 –

+2

@trojansdestroy不,他們不。那個參考文獻指的是什麼?他們通常會以價值回報。 – juanchopanza

+0

你如何處理兩個向量的大小不同?另外,你是否遵循[三規則](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29)? – juanchopanza

回答

0

因爲你的陣列(矢量)是在內存DINAMIC區。當你在函數中返回本地對象時,你必須有複製構造函數,並重載operator =。 但在較新版本的編譯器中,他們有優化,我認爲從標準C++ 11。優化是,如果編譯器在運行程序之前知道他應該返回什麼,他不會調用複製構造函數。