C++ 朋友和模板类
如何在不更改int数据状态的情况下编译以下代码C++ 朋友和模板类,c++,templates,C++,Templates,如何在不更改int数据状态的情况下编译以下代码 template<typename U> void Test(U); template< class T > class B { int data; public: friend void Test<>( T ); }; template<typename U> void Test(U u) { B < int> b1; b1.data = 7
template<typename U>
void Test(U);
template< class T >
class B {
int data;
public:
friend void Test<>( T );
};
template<typename U>
void Test(U u) {
B < int> b1;
b1.data = 7;
}
int main(int argc, char *argv[])
{
char i;
Test(i);
system("PAUSE");
return 0;
}
模板
孔隙试验(U);
模板
B类{
int数据;
公众:
朋友无效试验(T);
};
模板
孔隙试验(U){
Bb1;
b1.数据=7;
}
int main(int argc,char*argv[])
{
char i;
试验(i);
系统(“暂停”);
返回0;
}
上述代码导致编译器错误,因为使用VS2008编译的
b1.data
在Test
中是私有的U=char
。不确定是否符合标准
#include <cstdlib>
template<typename U> void Test(U);
template< class T > class B {
int data;
public:
template <typename U > friend void Test(U);
};
template<typename U>
void Test(U u){
B < int> b1;
b1.data = 7;
}
int main(int argc, char *argv[])
{
char i;
Test(i);
system("PAUSE");
return 0;
}
#包括
模板孔隙试验(U);
模板B类{
int数据;
公众:
模板失效试验(U);
};
模板
孔隙试验(U){
Bb1;
b1.数据=7;
}
int main(int argc,char*argv[])
{
char i;
试验(i);
系统(“暂停”);
返回0;
}
问题在于,您与测试成为B
的朋友(对于同一个U),但您试图从测试(不同的U)访问B
的内部
让任何B的测试成为朋友可能是最简单的。目前没有输出。预期的行为是什么?怎么了?@aman:你认为你写朋友无效测试(T)是在做什么代码>?尼尔,你能告诉我为什么我被标记为mod关注吗?@Neil@Aman帐户合并。不用担心。你创建了一个新帐户,它们被版主合并了。