1
如果我有這樣的層次:公共繼承的模板友元類
#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_作爲受保護屬性)?
即使模板類是朋友,這是否有效? – tmaric
我的意思是說,如果私有屬性在typeA中被聲明爲受保護,那麼它可能會更容易,在這種情況下,如果繼承是公共的,那麼它們可以通過typeB方法直接尋址。 – tmaric
@ tomislav-maric:是的。 – Nawaz