为什么这个内部朋友全局功能不能工作?

发布于 2025-01-10 00:15:44 字数 525 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栖竹 2025-01-17 00:15:44

类中定义的友元只能通过依赖于参数的查找找到,但是my_make_pair("hello", 2) 没有 myPair 类型的参数。所以不起作用。

该函数实际上不必是友元,因此可能只是一个自由函数(在类之外):

template<class T, class M>
myPair<T, M> my_make_pair(T f, M s){
    myPair<T, M> tmp(f, s);
    return tmp;
}

该函数被发现,但是...如“hello”< /code> 不是 std::string,无论如何调用都会返回错误类型的对。

可以通过显式指定类型来让赋值工作:

myPair<std::string, int> a = my_make_pair<std::string, int>("hello", 2);

但是这种方式会剥夺拥有 make 函数的用处。然后,您也可以使用构造函数直接构造该对:

myPair<std::string, int> a {"hello", 2};

A friend defined inside the class is only found by argument-dependent lookup, but my_make_pair("hello", 2) has no argument of type myPair. So doesn't work.

The function doesn't really have to be a friend, so could be just a free function (outside the class):

template<class T, class M>
myPair<T, M> my_make_pair(T f, M s){
    myPair<T, M> tmp(f, s);
    return tmp;
}

That function will be found, but ... as "hello"is not a std::string, the call would return the wrong type of pair anyway.

You could get the assignment to work by explicitly specifying the types:

myPair<std::string, int> a = my_make_pair<std::string, int>("hello", 2);

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:

myPair<std::string, int> a {"hello", 2};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文