我一直在向现有的Operator重载程序添加c ++模板,现在我收到了这些错误。 我无法纠正这些错误,任何人都可以帮助我...... 这是代码...... 我可以在简单的重载函数上模板但在朋友函数上有问题。 *****************注:(更新版) 整改后的代码...... / 程序演示操作员超载 / #include
template <class T>
class OP
{
T x, y, z;
public:
void IN()
{
std::cout << "Enter three No's : ";
std::cin >> x >> y >> z;
}
void OUT()
{
std::cout << std::endl << x << " " << y << " " << z;
}
void operator~();
void operator+(int); //Can accept both one or two argument
template<class TA>
friend void operator++(OP<T>); //Accept one arguments (Unary Operator);
template<class TB>
friend void operator-(OP<T>, int); //Accept two arguments (Binary Operator)
template<class TC>
friend void operator!=(OP&, char t);
};
template<class T>
void OP<T>::operator~() //Unary Member Operator
{
std::cout << std::endl << " ~ (tilde)";
}
template<class T>
void OP<T>::operator+(int y) //Binary Member Operator
{
std::cout << std::endl << "Argument sent is " << y;
}
template<class T>
void operator-(OP<T> &a, int t) //Binary Friend Operator
{
a.x= a.x-t;
a.y= a.y-t;
a.z= a.z-t;
}
template<class T>
void operator!=(OP<T> &q, char t) //Binary Friend Operator
{
std::cout << std::endl << "Char " << t;
}
template<class T>
void operator++(OP<T> x) //Unary Friend Operator
{
std::cout << std::endl << "Friend Unary Operator";
}
int main()
{
OP <int> n, m;
n.IN();
m.IN();
m+1;
n!='t';
int a = 1;
char r='r';
~n; //Member Function (Unary)
n-a; //Member Function (Unary)
operator-(m, a); //Friend Function (Binary)
operator++(m); //Friend Function (Unary)
n.OUT();
m.OUT();
std::cin.get();
return 0;
}
错误在所有三个友元函数上,错误是
现在我的朋友功能无法访问私人会员......&lt;&lt;&lt; 请告诉我我做错了什么......
答案 0 :(得分:3)
如果在模板类中声明了友元函数,则必须在模板类定义中提供定义,或者在模板类之外重新声明它。
在模板类中将其声明为朋友并不在封闭范围内声明该函数。