【发布时间】:2013-04-09 08:25:17
【问题描述】:
我的问题在于操作员*。我有两个与 Wektor 类连接的 operator*。首先是所有类型名,属于 Wektor 类。
friend Wektor operator* (Wektor & a, const int & b)
第二个仅用于字符串类型,并且在 Wektor 类之外。
template <typename T,int Roz, typename Policy >
Wektor<std::basic_string<char>,Roz,Fast<std::basic_string<char>,Roz> > operator * (Wektor<std::basic_string<char>,Roz,Fast<string,Roz> > & a,int & b)
我想要两个运算符*,其中一个专门用于字符串并且具有不同的行为。 以及下面的整个代码:
//Policy for Wektor
template<typename T,int Roz>
class Safe
{
public:
void static zeroo(T t[]){
for(int i=0;i<Roz;++i)
{
t[i]=0;
}
}
static bool isOut(int i){
return Roz<i;
}
};
template<typename T,int Roz>
class Fast
{
public:
void static zeroo(T t[]){
}
static bool isout(int i){
return false;
}
};
template<typename T,int Roz, typename Policy = Safe<T,Roz> >
class Wektor;
template <typename T,int Roz, typename Policy = Safe<T,Roz> >
Wektor<T,Roz,Policy> operator + (const Wektor<T,Roz,Policy> & a, const Wektor<T,Roz,Policy> & b);
template <typename T,int Roz, typename Policy >
Wektor<std::basic_string<char>,Roz,Fast<std::basic_string<char>,Roz> > operator * (Wektor<std::basic_string<char>,Roz,Fast<string,Roz> > & a, int & b);
template<typename T,int Roz, typename Policy >
class Wektor{
public:
typedef typename typy<T>::result args;
Wektor()
{
Policy::zeroo(tab);
}
T tab[Roz];
args get(int i)
{
if (Policy::isout(i)) return 0;
return tab[i];
}
void set(args val,int i)
{
if (Policy::isout(i))return;
tab[i]=val;
}
//This operator works fine
friend Wektor operator* (Wektor & a, const int & b){
Wektor<T,Roz,Policy> w;
for(int i=0;i<Roz;++i)
{
w.set(a.get(i)*b,i);
}
return w;
}
friend Wektor operator + <> (const Wektor & a, const Wektor & b);
};
template<typename T, int Roz>
Wektor<T,Roz> operator + (Wektor<T,Roz> & a,Wektor<T,Roz> & b)
{
Wektor<T,Roz> wynik;
for(int i=0;i<Roz;++i)
{
wynik.set(a.get(i)+b.get(i),i);
}
return wynik;
}
//This operator dosent work
template <typename T,int Roz, typename Policy >
Wektor<std::basic_string<char>,Roz,Fast<std::basic_string<char>,Roz> > operator * (Wektor<std::basic_string<char>,Roz,Fast<string,Roz> > & a,int & b)
{
Wektor<string,Roz,Fast<string,Roz> > wynik;
string tmp;
for(int i=0;i<Roz;++i)
{
for(int j;j<b;++j)tmp.append("asa");
wynik.set(tmp,i);
tmp.clear();
}
}
main() 中的 For 语句:
Wektor<string,2,Fast<string,2> > str;
str*3
我在这一行得到一个错误:
w.set(a.get(i)*b,i);
在朋友运算符*中,它在 Wektor 类中是完整的。
编译器说:模板参数推导/替换失败。 其余编译器说明:
错误:'Wektor::get(int) 中的'operator*' 不匹配,T = std::basic_string;诠释罗兹 = 2;策略=快速,2>; Wektor::args = std::basic_string * b'
还有更多:
注意:候选人是: 注意:模板 Wektor, Roz, Fast, Roz> > operator*(Wektor, Roz, Fast, Roz> >&, int&)
注意:'Wektor, 2, Fast, 2> >::args {aka std::basic_string}' 不是从 'Wektor, Roz, Fast, Roz>>'|
在这种情况下不是源自的意思是什么?我尝试使用 Wektor 类将专门的 operator* 作为 firend,但这会产生同样的错误。
【问题讨论】:
-
请不要用波兰语编写代码。此外,
std::basic_string<char>只是std::string。也看看operator overloading FAQ。 -
并将
operator+和operator*的第一个参数作为const引用。