尝试过载时的错误<<操作员和使用朋友功能 [英] error when trying to overload << operator and using friend function
问题描述
我尝试过载<
下面的代码块工作正常。
I am trying to overload << operator and using friend function. Below code chunk works just fine.
template <class T>
class Mystack{
friend std::ostream& operator<<(std::ostream& s, Mystack<T> const& d)
{
d.print(s);
return s;
}
};
因为它是friend函数,我显然需要在类外定义它,而不使用范围解析操作符。但是当我尝试,我得到错误。
Since it is friend function I would obviously want to define it outside the class without using scope resolution operator. But when I try that I get error.
template <class T>
class Mystack{
friend std::ostream& operator<<(std::ostream& s, Mystack<T> const& d);
};
template <class T>
std::ostream& operator<<(std::ostream& s, Mystack<T> const& d)
{
d.print(s);
return s;
}
以下是主要的代码片段
Mystack<int> intstack;
std::cout << intstack;
ERROR :未解析的外部符号。
ERROR : Unresolved extrernal symbol.
PS:它不是完整的运行代码。只是一个样本。亲爱的。
P.S: Its not the complete running code. Just a sample. Kindly bear.
推荐答案
friend std::ostream& operator<<(std::ostream& s, Mystack<T> const& d);
声明并结合非模板运算符<<
函数。因此 Mystack< int>
会有一个非模板函数 std :: ostream& <<<<(std :: ostream& s,Mystack< int> const& d);
等。
declares and befriends a non-template operator<<
function. So Mystack<int>
would have as its friend a non-template function std::ostream& operator<<(std::ostream& s, Mystack<int> const& d);
, etc.
template<class T>
std::ostream& operator<<(std::ostream& s, Mystack<T> const& d)
{
d.print(s);
return s;
}
定义运算符<<
函数模板。
两者不一样。当你写 std :: cout<< intstack;
,重载解析规则将其解析为您声明的非模板运算符<
函数,但未定义,因此你会得到一个链接器错误。
The two are not the same. When you write std::cout << intstack;
, the overload resolution rules resolve it to the non-template operator<<
function you declared, but it isn't defined, so you get a linker error.
没有办法为类模板之外的类模板的每个实例化定义一个非模板函数。但是,您可以将您的运算符<< <
功能模板的专业化:
There's no way to define a non-template function for every instantiation of a class template outside the class template. You can, however, befriend a specialization of your operator<<
function template:
// forward declarations
template <class T>
class Mystack;
template <class T>
std::ostream& operator<<(std::ostream& s, Mystack<T> const& d);
template <class T>
class Mystack
{
friend std::ostream& operator<< <T>(std::ostream& s, Mystack<T> const& d);
// ^^^
};
或者担心函数模板的每一个特化,从封装的观点来看,例如 operator
将是 Mystack< float>
的朋友):
or befriend every specialization of the function template, which is worse from an encapsulation point of view (since, e.g., operator<< <int>
would be a friend of Mystack<float>
):
template <class T>
class Mystack
{
public:
template <class U>
friend std::ostream& operator<<(std::ostream& s, Mystack<U> const& d);
};
或只是在类中定义friend函数。
or just define the friend function inside the class.
这篇关于尝试过载时的错误<<操作员和使用朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!