【发布时间】:2011-11-17 11:01:25
【问题描述】:
如果我有这种层次结构:
#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 是一种列表容器:您认为这种关系的动机是什么(公共继承 + 朋友,如果需要直接访问,则将 x_ 和 size_ 作为受保护的属性)?
【问题讨论】:
标签: c++ templates inheritance public