类继承和重新定义成员类型 c++

Class inheritance and redefining type of members c++

本文关键字:成员 成员类 类型 c++ 定义 继承 新定义      更新时间:2023-10-16

>假设我们有一个名为 Base 的类。在此类中,有一个向量和在此向量上运行的函数。我想创建基于向量类型的不同派生类(一个继承的类用于 int,另一个用于 char...等(。对于不同的派生类,有些方法完全相同(int,char,bool...(,其他方法则完全不同。这些方法需要访问矢量元素。

请考虑以下代码:

class Base {
public:
    std::vector<int> vec;
    virtual void Print() { std::cout << vec[0]; }
};
class Derived : public Base {
public:
    std::vector<bool> vec;
};
int main() {
    Base * test = new Derived;
    test->vec.push_back(5);
    test->Print();
    system("PAUSE");
}

这将打印一个整数而不是布尔值。

不能仅通过派生基类中向量来更改向量的类型。派生类具有基类的所有成员,以及它自己的成员。

在您的代码中,派生类作为vector<int>vector<bool>。调用的Print函数是基类的Print函数,因为派生类不实现自己的函数。基类的 Print 函数打印vector<int>

您需要使用模板而不是继承。您可以执行以下操作:

template <class T>
class Generic {
public:
    std::vector<T> vec;
    void Print() { std::cout << vec[0]; }
};
int main() {
    Generic<bool> * test = new Generic<bool>;
    test->vec.push_back(5);
    test->Print();
    system("PAUSE");
}

在上面的代码中,Generic 是一个保存 T 向量的类(其中 T 可以是 int、bool 等等(。您可以通过指定类型来实例化特定类型的类,例如 Generic<bool> . Generic<bool>不同于Generic<int>,不同于Generic<double>等,就像vector<int>不同于vector<bool>等一样。