所以我試圖建立一個關於羣理論和邏輯的研究項目的模板類。我有班級: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;
}
你這樣做是錯誤的:你的運營商都是二元運算符應返回'CSet'。變異的二元運算符是@ =,它應該返回'CSet &'。 –