0

假设我们有一个名为 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");
}

这会打印一个 int 而不是 boolean。

4

1 回答 1

2

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

在您的代码中,派生类为 a vector<int>AND a 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>is different from , Generic<int>which is different fromGeneric<double>vector<int>vector<bool>

于 2013-04-21T01:57:10.907 回答