如果我有这种层次结构:
#include <iostream>
using namespace std;
template<class T>
class typeB;
template<class T>
class typeA
{
// Private data
T* x_;
int size_;
public:
// Constructors
typeA()
: x_(0), size_(0)
{
};
typeA(int size)
: x_(0), size_(size)
{
}
// Friend classes.
friend class typeB<T>;
};
template<class T>
class typeB
: public typeA<T>
{
public:
// Constructors
typeB ()
{
};
typeB (int size)
: typeA<T>(size)
{
//this->x_ = new T[size];
x_ = new T[size];
}
};
int main()
{
typeB<int> b(4);
return 0;
}
为什么我需要在 typeB(int size) 构造函数中指定“this->x_ = new T[size]”而不是“x_ = new T[size]”来编译此代码?
编译器告诉我的是它无法解析 x_ 的类型:
main.cpp: In constructor ‘typeB<T>::typeB(int)’:
main.cpp:42: error: ‘x_’ was not declared in this scope
如果 typeB 是 typeA 的友元,它应该可以公开访问 typeA 的属性。如果我用非模板类尝试这个,它会起作用:
#include <iostream>
using namespace std;
class typeB;
class typeA
{
// Private data
int* x_;
int size_;
public:
// Constructors
typeA()
: x_(0), size_(0)
{
};
typeA(int size)
: x_(0), size_(size)
{
}
// Friend classes.
friend class typeB;
};
class typeB
: public typeA
{
public:
// Constructors
typeB ()
{
};
typeB (int size)
: typeA(size)
{
x_ = new int[size];
}
};
int main()
{
typeB b(4);
return 0;
}
typeA 和 typeB 是一种列表容器:您认为这种关系的动机是什么(公共(public)继承 + friend ,如果需要直接访问,则将 x_ 和 size_ 作为 protected 属性)?
最佳答案
首先,成员x_
是基类的私有(private)成员。在这里友元不会有帮助,因为您正试图通过继承访问成员。
即使将其设置为 protected 或公开,模板基类的成员也不会自动在派生类中可见。
解决方案是:
明确使用
this->
作为,this->x_ = new int[size];
或者将名称引入派生类范围:
template<class T> class typeB : public typeA<T> { using typeA<T>::x_; //brings the name x_ into the class scope! //...
然后你就可以写了
x_ = new int[size];
关于c++ - 公共(public)继承模板友元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166003/