c++ - 初始化继承的成员数据

标签 c++

<分区>

我有以下类(class):

template <class S, class T>
class Pair {

protected:
    S data1;
    T data2;

public:
  ...
}

template <class S, class T>
class Node: public Pair<const KeyType, DataType> {

private:
    Node<const S, T>* next;

public:

    //C'tor
    Node(const KeyType& sKey, const DataType& sData) :
    data1(sKey), data2(sData), next(NULL) {
    }

    //Copy C'tor
    Node(const Node<KeyType, DataType>& sNode):
    data1(sNode.getData1()), data2(sNode.getData2()), next(NULL) {
    }

    ...
};

但由于某些原因,我无法使用 Node 从 Pair 继承的 data1 和 data2。 我收到以下错误:

./map.h:24:5: error: use of undeclared identifier 'data1'
                                data1 = sKey;
                                ^
./map.h:25:5: error: use of undeclared identifier 'data2'
                                data2 = sData; 
                                ^
./map.h:30:4: error: member initializer 'data1' does not name a non-static data member or base class
                        data1(sNode.getData1()), data2(sNode.getData2()), next(NULL) {
                        ^~~~~~~~~~~~~~~~~~~~~~~
./map.h:30:29: error: member initializer 'data2' does not name a non-static data member or base class
                        data1(sNode.getData1()), data2(sNode.getData2()), next(NULL) {
                                                 ^~~~~~~~~~~~~~~~~~~~~~~

我做错了什么?

*这是我的硬件作业的一部分,所以我不能使用来自 STL 的对。

最佳答案

虽然您可以像我在评论中建议的那样,通过在数据成员前面加上类名来查看数据成员;一个更好的主意是为 Pair 创建一个构造函数:

template <class S, class T>
class Pair {

protected:
    S data1;
    T data2;

public:
  Pair(const S & d1, const T & d2) : data1( d1), data2( d2) { }
  ...
} ;

然后你可以通过以下方式初始化Pair:

Node(const KeyType& sKey, const DataType& sData) :
  Pair(sKey, sData), next(NULL)
  ...

关于c++ - 初始化继承的成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011471/

相关文章:

c++ - 为什么像 std::is_permutation() 这样的函数本质上不是不安全的?

c++ - C++中的'rand'函数?

c++ - 编写跨平台代码时使用 char* 而不是 void* 有什么陷阱吗?

c++ - 旋转后找到三角形的点

c++ - 在 C++ 中打印 float 的二进制表示

c++ - 仅保留重复值 - Vectors C++

c++ - boost asio tcp 线程化。等待新 sample ?

c++ - VS2010 : Collapse code regions only works for . c 文件,不适用于 .cpp 文件

c++ - 使用FFmpeg以编程方式创建视频,使用SDL的 Sprite 截图BMP

c++ - 澄清琐碎的破坏者