【发布时间】:2014-05-10 03:22:28
【问题描述】:
我正在尝试为我创建的模板类重载“+”、“-”和“/”运算符。 + 和 - 运算符完美运行,但 / 运算符重载给了我错误。
我正在使用 Visual Studio 2013
//Set.h
#pragma once
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class Set
{
friend Set<T> operator+ <> (const Set& left, const Set& right); //works
friend Set<T> operator- <> (const Set& left, const Set& right); //works
friend Set<T> operator/ <> (const Set& left, const Set& right); //does not
public:
Set(int n)
{
numItems = n;
setItems();
}
Set()
{
numItems = 0;
setItems();
}
~Set();
void setItems();
void output();
private:
int numItems;
vector<T> set;
};
我想重载 / 运算符以确定intersection of two sets
定义:
//---------------- Overload intersection -----------------
template<class T>
Set<T> operator/(const Set<T>& left, const Set<T>& right)
{
bool putin = false;
Set<T> quotient;
// loops through left Set
for (int i = 0; i < left.set.size(); i++)
{
for (int j = 0; j < right.set.size(); j++)
//loops through right set
{
//checks if the item in left is in right set
// if it is, PUT IT IN the new set
if (left.set[i] == right.set[j])
putin = true;
}
if (putin)
quotient.set.push_back(left.set[i]);
putin = true;
}
return quotient;
}
这是我遇到的错误
Error 1 error C2143: syntax error : missing ';' before '<'
Error 2 error C2460: '/' : uses 'Set<T>', which is being defined
Error 3 error C2433: '/' : 'friend' not permitted on data declarations
Error 4 error C2238: unexpected token(s) preceding ';'
Error 5 error C2365: '/' : redefinition; previous definition was 'data variable'
Error 6 error C2904: '/' : name already used for a template in the current scope
Error 7 error C2460: '/' : uses 'Set<int>', which is being defined
【问题讨论】:
标签: c++ operator-overloading template-classes