2017-10-18 34 views
0

我正在寫與非類型參數的模板類具有非類型參數的C++模板類:如何重載賦值運算符?

class Test 
{ 
public: 
    Test() { std::cout << "Test::Test()" << std::endl; } 

    Test(Test const&) { std::cout << "Test::Test(Test const&)" << std::endl; } 

    ~Test() { std::cout << "Test::~Test()" << std::endl; } 

    Test& operator=(Test const&) 
    { 
      std::cout << "Test& Test::operator=(Test const&)" << std::endl; 
      return *this; 
    } 

    void print() const { std::cout << "Test::print() const" << std::endl; } 
    void print() { std::cout << "Test::print()" << std::endl; } 
}; 

以上就是我的「測試」類來測試我的模板類和

template <typename T, unsigned int n> 
class Array 
{ 
private: 
    T* value; 
public: 
    Array() { 
     this->value = new T[n]; 
    } 

    ~Array() { 
     delete[] this->value; 
    } 

    Array* operator=(const Array* arr) 
    { 
     this->value = arr->value; 
     return this->value; 
    } 

    T& operator[](int a) { 
     return this->value[a]; 
    } 

    unsigned int size() 
    { 
     return n; 
    } 
}; 

以上是我的模板類與非型參數。

int main(int, char*[]) 
{ 
/*first*/ Array<Test, 3> arr_1; 

/*second*/ Array<Test, 3> arr_3 = arr_1; 

return 0; 
} 

在我的main.cpp文件,

我做一流的檢測對象與第一個3次,

,我想重載賦值運算符做第二個。

Array* operator=(const Array* arr) 
{ 
    this->value = arr->value; 
    return this->value; 
} 

但 '段錯誤' 嘗試無限調用析構函數後。

我想知道如何在這種情況下編寫賦值運算符重載。

謝謝!

+0

通常,賦值運算符會將*引用*接收到相同類型的對象,而不是*指針*。那是故意的嗎? – templatetypedef

+0

'Array arr_3 = arr_1;'使用拷貝構造函數,而不是拷貝賦值操作符。無論如何,'Array'並沒有明確的實現;兩者都是隱含定義的。 –

+0

@templatetypedef,我試着用Array&operator =(const Array&arr),但它沒有改變結果。也許我沒有正確實施該方法。 –

回答

1

要實現複製,你需要的東西是這樣的:

// Copy constructor. When you write Array b = a, the compiler actually calls this, not operator= 
Array(const Array& src) 
{ 
    this->value = new T[ n ]; 
    std::copy_n(src.value, n, value); 
} 
Array& operator=(const Array& src) 
{ 
    // No need for new[], operator= is called after the object is already constructed. 
    std::copy_n(src.value, n, value); 
    return *this; 
} 

但是,你不應該重新發明輪子。 C++標準庫中已經有像樣的模板類。如果您的陣列很小(例如3個),請使用std::array<Test, 3>。如果您的陣列很大並且想要將它們從堆棧中取出,則可以使用std::unique_ptr<std::array<Test, 3>>std::vector<Test>

+0

非常感謝您的回答! –