【发布时间】:2015-12-04 04:58:29
【问题描述】:
举一个简单的例子,有两个相关的问题。源代码 - 3个文件:
父.h:
#ifndef PARENT_H
#define PARENT_H
using namespace std;
#include <vector>
template <class CHILD_TYPE>
class PARENT
{
public:
class CHILD_DATA
{
public:
vector<CHILD_TYPE *> child_ptrs;
void dump_child_data();
};
static CHILD_DATA data;
};
template<class CHILD_TYPE>
void PARENT<CHILD_TYPE>::CHILD_DATA::dump_child_data()
{
return;
}
#endif /* PARENT_H */
child.h
#ifndef CHILD_H
#define CHILD_H
#include "parent.h"
using namespace std;
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
class SPECIAL_CHILD : public PARENT<SPECIAL_CHILD>
{
public:
SPECIAL_CHILD (const string newname = "unnamed") : name (newname) {}
string name;
};
template<>
void PARENT<SPECIAL_CHILD>::CHILD_DATA::dump_child_data()
{
for (vector<SPECIAL_CHILD *>::iterator it = child_ptrs.begin(); it != child_ptrs.end(); it++)
{
cout << (*it)->name << endl;;
}
return;
}
#endif /* CHILD_H */
main.cpp
#include <cstdlib>
#include "parent.h"
#include "child.h"
using namespace std;
int main(int argc, char** argv) {
SPECIAL_CHILD c_a;
SPECIAL_CHILD c_b("named");
SPECIAL_CHILD c_c("named_again");
c_a.data.dump_child_data();
return 0;
}
问题 1: 此示例未构建:
main.cpp:12:未定义对 `PARENT::data' 的引用
为什么? Parent的成员名为data是公共的,我不能像自己的成员一样从子类对象访问它吗?
问题 2:如何在超类中为子类创建专用模板 - 在我的例子中,模板参数是指向子类对象的指针?我绝对不希望超类知道有关子类的任何信息。我应该像我一样将专门的模板定义放在子类标题中吗?或者甚至在子类 .cpp 中,如果存在的话?
谢谢。
【问题讨论】:
-
避免使用
using namespace,尤其是在头文件中。
标签: c++ templates inheritance template-specialization