类继承和重新定义成员类型 c++
Class inheritance and redefining type of members c++
>假设我们有一个名为 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>
等一样。
相关文章:
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 使用成员在类中创建 lambda 表达式
- 使用静态成员声明类时遇到问题
- 没有公共构造函数作为另一个类模板成员的类模板
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 具有 STL 向量类型成员的类的复制内存
- 内存中类位置的成员是否取决于类成员在类定义中的位置?
- C++成员变量类Q_PROPERTY QML 中不可用
- 提升 - 类没有名为"序列化"的成员(抽象类)?
- C++ - 移动具有固定大小的 c 样式数组成员的类的构造函数
- 具有未知结构作为成员的类
- 清除具有已删除赋值运算符的成员的类实例
- 错误:请求成员 .. 是非类类型"char"
- 没有成员的类的<运算符
- 从相同类型的静态成员进行类内初始化
- 如何设计一个始终是另一个类的成员的类
- 使用 Boost::Serialization 序列化具有 std::mt19937_64 成员的类
- C++ 将队列作为成员的类的构造函数和析构函数
- 移动具有常量成员的类的构造和分配
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?