我在模板类之外定义operator%时遇到问题。我在里面解决了这个问题,但我想知道为什么它不起作用。
这是我的代码:
namespace std{
class vector{};class deque{};class list{};class multiset{};class set{}; class map{}; class multimap{};
};
//---------------------------------------
namespace oop{
template<typename T> class Array{
public:
class value_type{
public:
value_type(T val):_val(val){};
T _val;
};
Array(int size);
Array& insert(T ob);
virtual ~Array(){delete [] _arr;};
static unsigned int _inserted;
T& operator[](int i){return _arr[i];};
Array& operator%(const value_type& right){this->insert(right._val);Array& ref=*this; return ref;}; // inside class it works fine
unsigned int operator~(){return _inserted;}
private:
T* _arr;
int _size;
};
template<typename T> unsigned int Array<T>::_inserted=0;
template<typename T> Array<T>::Array(int size){
_size=size;
_arr=new T[size];
}
template<typename T> Array<T>& Array<T>::insert(T ob){
_arr[Array<T>::_inserted]=ob;
Array<T>::_inserted++;
Array<T>& ref=*this;
return ref;
}
// But outside it throws an error during compilation: "'oop::Array<T>::value_type' is not a type"
//
// |
// v
//
// template<typename T> Array<T>& operator%(Array<T>& left, Array<T>::value_type & right){
// left.insert(right._val);
// return left;
// }
};
//---------------------------------------
#include<cstdlib>
#include<iostream>
//---------------------------------------
int main(){
typedef oop::Array<char> type;
type a(rand()%10+5);
a.insert('#').insert('C')%type::value_type('P')%type::value_type('P')%'&';
for(unsigned int i=0; i!=~a; ++i)
std::cout<<i<<":"<<a[i]<<((i+1)!=~a?" ":"\n");
return 0;
}
//output: 0:# 1:C 2:P 3:P 4:&
编译器似乎将type_value视为除了type之外的其他内容,为什么呢?