为什么这个内部朋友全局功能不能工作?
template<class T, class M>
struct myPair{
friend myPair<T, M> my_make_pair(T f, M s){
myPair<T, M> tmp(f, s);
return tmp;
}
T first;
M second;
myPair(){};
myPair(T f, M s){
this->first = f;
this->second = s;
}
};
int main(){
myPair<string, int> a = my_make_pair("hello", 2);
cout << a.first << " " << a.second << endl;
}
错误表示:“my_make_pair”现在在此范围内声明。但为什么以及如何?真的很迷茫......
template<class T, class M>
struct myPair{
friend myPair<T, M> my_make_pair(T f, M s){
myPair<T, M> tmp(f, s);
return tmp;
}
T first;
M second;
myPair(){};
myPair(T f, M s){
this->first = f;
this->second = s;
}
};
int main(){
myPair<string, int> a = my_make_pair("hello", 2);
cout << a.first << " " << a.second << endl;
}
the error saids: "my_make_pair" was now declare in this scope. But why and how to ?? Really confused.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类中定义的友元只能通过依赖于参数的查找找到,但是
my_make_pair("hello", 2)
没有myPair
类型的参数。所以不起作用。该函数实际上不必是友元,因此可能只是一个自由函数(在类之外):
该函数将被发现,但是...如
“hello”< /code> 不是
std::string
,无论如何调用都会返回错误类型的对。您可以通过显式指定类型来让赋值工作:
但是这种方式会剥夺拥有 make 函数的用处。然后,您也可以使用构造函数直接构造该对:
A friend defined inside the class is only found by argument-dependent lookup, but
my_make_pair("hello", 2)
has no argument of typemyPair
. So doesn't work.The function doesn't really have to be a friend, so could be just a free function (outside the class):
That function will be found, but ... as
"hello"
is not astd::string
, the call would return the wrong type of pair anyway.You could get the assignment to work by explicitly specifying the types:
but that kind of takes away the usefulness of having a make-function. You could then just as well construct the pair directly, using the constructor: