C++ 入门:模板和函数
template <typename>
class BlobPtr;
template <typename>
class Blob;
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob
{
friend class BlobPtr<T>;
friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
};
然后:
Blob<char> ca;
Blob<int> ia;
The members of
BlobPtr<char>
may access the nonpublic parts of ca (or any other Blob object), but ca has no special access to ia (or any other Blob) or to any other instantiation of Blob.
问题: 我想测试代码。如何使用 ca 访问 ia 的非公开部分?澄清一下,我知道这是不可能的,但我想测试代码以查看错误。
最佳答案
您可以只添加 template
使用前 friend
.
template<typename T>
class Blob
{
template<typename T1>
friend class Blob;
public:
template<typename T1>
bool operator==(const Blob<T1>& other)
{
return i == other.i;
}
private:
T i;
};
Blob<int> i;
Blob<char> j;
int main()
{
i == j;
}
添加模板使得每个Blob<T>
类(class)变成了彼此的 friend 类(class)。所以,Blob<int>
的每个成员函数可以访问 Blob<char>
的私有(private)成员反之亦然。
关于c++ - 模板类和 Friend 模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51255357/