2015-06-03 160 views
1

所以我試圖建立一個關於羣理論和邏輯的研究項目的模板類。我有班級:C++模板類運算符重載

#pragma once 
#include <iostream> 
#include <assert.h> 
using namespace std; 
template <class T> 
class CSet 
{ 
private: 
    T* arr; 
    int size; 
protected: 

public: 
    /*Constructors & Destructor*/ 
    CSet(int s = 0, T* a = NULL); //Default constructor 
    CSet(const CSet<T> & obj_input); //Copy constructor 
    ~CSet() { delete[] arr; } //Destructor 

    /*Operators Overloading*/ 
    const CSet<T>& operator=(const CSet<T>& obj_input); // = overloading 
    const CSet<T>& operator+=(const T& val_input); // += overloading 
    const CSet<T>& operator-=(const T& val_input); // -= overloading 

    /*Logic Operators Overloading*/ 
    const CSet<T>& operator|(const CSet<T>& obj_input); 
    const CSet<T>& operator&(const CSet<T>& obj_input); 
    const CSet<T>& operator-(const CSet<T>& obj_input); 
    bool operator==(const CSet<T>& obj_input); 
    bool operator!=(const T& val_input); 
    bool operator>(const CSet<T>& obj_input); 
    const CSet<T>& operator^(const CSet<T>& obj_input); 

    //void DifWrite(const CSet<T>& obj_input); //does - and outputs to file 

    friend ostream& operator<<(ostream& op, const CSet<T>& input) { 
     for (int i = 0; i < input.size; i++) 
     { 
      op << input.arr[i] << " "; 
     } 
     return op; 
    } 
}; 

我試圖使|操作員模擬OR邏輯功能。這意味着如果我使A = {1,2,3}和B = {3,4,5},那麼A | B = {1,2,3,4,5}這是一個新的對象。但是我不能解釋如何爲新對象分配內存並返回它。我公司目前擁有的功能正在改變「這個」,而不是返回一個新的對象:

template <class T> 
const CSet<T>& CSet<T>::operator|(const CSet<T>& obj_input) { 
    if (!arr) 
    { 
     *this = obj_input; 
     return *this; 
    } 
    else if (!obj_input.arr) 
    { 
     return *this; 
    } 
    else 
    { 
     for (int i = 0; i < size; i++) 
     { 
      temp += this->arr[i]; 
     } 
     for (int i = 0; i < obj_input.size; i++) 
     { 
      temp += obj_input.arr[i]; 
     } 
     *this = temp; 
    } 
    return *this; 
} 
+3

你這樣做是錯誤的:你的運營商都是二元運算符應返回'CSet '。變異的二元運算符是@ =,它應該返回'CSet &'。 –

回答

1

你不想返回一個常量引用您正在創建函數的對象。你應該做的是在函數中創建一個對象,然後按值返回。要做到這一點你的代碼是:

template <class T> 
CSet<T> CSet<T>::operator|(const CSet<T>& obj_input) const 
{ 
    CSet<T> temp; 
    temp.size = *this.size + obj_input.size; 
    temp.arr = new T[temp.size]; 
    int i = 0; 
    for (; i < *this.size; i++) 
     temp.arr[i] = *this.arr[i]; 
    for (; i - *this.size < obj_input.size; i++) 
     temp.arr[i] = *this.arr[i]; 
    return temp; 
} 

如果改爲使用std::vector而不是原始陣列的功能將成爲:

template <class T> 
CSet<T> CSet<T>::operator|(const CSet<T>& obj_input) const 
{ 
    CSet<T> temp; 
    temp.arr.insert(temp.arr.end(), *this.arr.begin(), *this.arr.end()); 
    temp.arr.insert(temp.arr.end(), obj_input.arr.begin(), obj_input.arr.end()) 
    return temp; 
} 
+0

你錯過了工會邏輯,但想法就在這裏。順便說一下,運算符可能是'const' – Jarod42

+0

那麼我可以在返回值上使用const還是不是?我們不允許使用std :: vector。 –

+0

@adam如果你正在返回值沒有理由使返回常量。你可以使功能不斷思考。 – NathanOliver