【发布时间】:2011-09-04 18:34:55
【问题描述】:
我正在尝试向 C++ 中的嵌套结构添加一些额外的字段,并且设计要求我希望通过继承来实现。我收到一个错误,奇怪的是,我使用的是 T* 类型还是 T** 类型。我很困惑,希望有人帮助我了解这里发生的事情。
嵌套结构是 Base::Node,我想向 Base::Node 添加一个字段 b,然后使用 Derived,如主文件所示。当我将顶部的#define 设置为 0 时,一切都会编译并正常工作。当我将 #define 更改为 1 时,我收到以下编译器错误:
main_inhtest.cpp: In instantiation of ‘Derived<int>’:
main_inhtest.cpp:52: instantiated from here
main_inhtest.cpp:44: error: conflicting return type specified for ‘Derived<T>::DNode** Derived<T>::GetNAddr() [with T = int]’
main_inhtest.cpp:24: error: overriding ‘Base<T>::Node** Base<T>::GetNAddr() [with T = int]’
main_inhtest.cpp: In member function ‘Derived<T>::DNode** Derived<T>::GetNAddr() [with T = int]’:
main_inhtest.cpp:57: instantiated from here
main_inhtest.cpp:44: error: invalid static_cast from type ‘Base<int>::Node**’ to type ‘Derived<int>::DNode**’
谁能帮我理解
这是否是正确的方法,是否有更好的方法,以及
为什么编译器对 GetN() 方法满意,但对 GetNAddr() 方法不满意?
谢谢!
#include <iostream>
#define TRY_GET_N_ADDR 1
template <typename T> class Base {
public:
Base() { n = new Node(); }
struct Node
{
T a;
};
virtual Node *GetN() { return n; }
virtual Node **GetNAddr() { return &n; }
Node *n;
};
template <typename T> class Derived : public Base<T> {
public:
Derived() { Base<T>::n = new DNode(); }
struct DNode : Base<T>::Node
{
T b;
};
// This method is fine
DNode *GetN() { return static_cast<DNode *>(Base<T>::GetN()); }
#if TRY_GET_N_ADDR
// Compiler error here
DNode **GetNAddr() { return static_cast<DNode **>(Base<T>::GetNAddr()); }
#endif
};
int main (int argc, const char * argv[]) {
Derived<int> d;
d.GetN()->a = 1;
d.GetN()->b = 2;
std::cout << d.GetN()->a << " " << d.GetN()->b << std::endl;
}
【问题讨论】:
标签: c++ templates inheritance nested-class