公共继承的模板友元类
问题描述:
如果我有这样的层次:公共继承的模板友元类
#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;
}
为什么我需要指定“这个 - > X_ =新的T [尺寸]”中的TypeB(INT大小)构造函数,而不是“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继承+朋友的动机,VS如果需要直接访问,将x_和size_作为受保护属性)?
答
首先,成员x_
是基类的私有成员。在这里,友谊不会帮助你,因为你试图访问到继承。
即使您对其进行保护或公开,模板基类的成员也不会在派生类中自动显示。
的解决方案是:
-
使用
this->
明确的, -
或将名称为派生类范围为:
template<class T> class typeB : public typeA<T> { using typeA<T>::x_; //brings the name x_ into the class scope! //...
,那么你可以写
x_ = new int[size];
即使模板类是朋友,这是否有效? – tmaric
我的意思是说,如果私有属性在typeA中被声明为受保护,那么它可能会更容易,在这种情况下,如果继承是公共的,那么它们可以通过typeB方法直接寻址。 – tmaric
@ tomislav-maric:是的。 – Nawaz