2

我试图将一个全局函数声明为一个类的“朋友”:

namespace first
{
    namespace second
    {
        namespace first
        {
            class Second
            {
                template <typename T> friend T ::first::FirstMethod();
            };
        }
    }
}

当我在 Visual C++ 2008 下编译这段代码时,我得到:

error C3254: 'first::second::first::Second' : class contains explicit override 'FirstMethod' but does not derive from an interface that contains the function declaration
error C2838: 'FirstMethod' : illegal qualified name in member declaration

如果我template <typename T> friend T first::FirstMethod();改用,我会得到:

error C2039: 'FirstMethod' : is not a member of 'first::second::first'

声明友元函数的适当方式是什么?

4

1 回答 1

5

你不小心打到了我的测验——这个序列T ::first:: ...被解释为一个名字。您需要在冒号和T. 解决方案也出现在链接的问题中。

请注意,在任何情况下,您首先也必须在其各自的命名空间中声明由限定名称指定的函数。


编辑:语法问题有不同的解决方案

 template <typename T> friend T (::first::FirstMethod)();
 template <typename T> T friend ::first::FirstMethod();

如果你经常需要引用外部命名空间并且对这种语法有问题,你可以引入命名空间别名

    namespace first
    {
        namespace outer_first = ::first;
        class Second
        {
            template <typename T> friend T outer_first::FirstMethod();
        };
    }
于 2010-07-02T17:08:26.260 回答