对于friend
的用法,C++11
新添加了下面两个
friend simple-type-specifier ; //(1)
friend typename-specifier ; //(2)
对于(1),在C++11之前,下面的代码是无法编译通过的
#include <iostream>
class B
{};
class A
{
int b;
friend B;
};
int main()
{
return 0;
}
你会得到如下的编译错误:
/home/insights/insights.cpp:8:10: warning: unelaborated friend declaration is a C++11 extension; specify 'class' to befriend 'B' [-Wc++11-extensions]
friend B;
^
class
1 warning generated.
要想编译成功的化,需要将friend B;
改为friend class B;
。
对于(2),C++11之前同样无法编译通过
#include <iostream>
#include <vector>
class B
{};
typedef std::vector<B> BVec;
class A
{
int b;
friend typename BVec::value_type;
};
int main()
{
return 0;
}
编译错误为:
/home/insights/insights.cpp:12:10: warning: 'typename' occurs outside of a template [-Wc++11-extensions]
friend typename BVec::value_type;
^~~~~~~~~
/home/insights/insights.cpp:12:10: warning: unelaborated friend declaration is a C++11 extension; specify 'class' to befriend 'typename BVec::value_type' (aka 'B') [-Wc++11-extensions]
friend typename BVec::value_type;
^
class
2 warnings generated.
网友评论