【发布时间】:2011-02-18 21:23:01
【问题描述】:
为什么
class A;
template<typename T> class B
{
private:
A* a;
public:
B();
};
class A : public B<int>
{
private:
friend B<int>::B<int>();
int x;
};
template<typename T>
B<T>::B()
{
a = new A;
a->x = 5;
}
int main() { return 0; }
结果
../src/main.cpp:15:错误:将构造函数用作模板无效
../src/main.cpp:15: 注意:使用'B::B'而不是'B::class B'以限定名称命名构造函数
但将 friend B<int>::B<int>() 更改为 friend B<int>::B() 会导致
../src/main.cpp:15: 错误:没有在类“B”中声明的“void B::B()”成员函数
同时完全删除模板
class A;
class B
{
private:
A* a;
public:
B();
};
class A : public B
{
private:
friend B::B();
int x;
};
B::B()
{
a = new A;
a->x = 5;
}
int main() { return 0; }
编译和执行都很好——尽管我的 IDE 说朋友 B::B() 语法无效?
【问题讨论】:
-
Visual C++ 2008 也不接受
friend B<int>::B(),但 Comeau 接受。 -
Visual C++ 2008 接受
friend B<int>::B<int>(),即使禁用了语言扩展。为什么 GCC (4.1) 不接受它? -
如果其他人不知道(我不知道),构造函数可以被声明为朋友:open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#263
-
@James:感谢那个链接,我很高兴看到 N4411 包含它。
-
gcc 很高兴与朋友 B
::B();
标签: c++ templates gcc constructor friend