如何使用抽象类中未包含的方法
How to use method that is not included in abstract class
例如,如果我有一个只有 2 个虚函数的抽象类I_Student:
-
void set() = 0
-
void print() = 0
以及包含其他函数的派生类 Student。
如果我声明的指针类型为 I_Student*,则指向 Student 对象
I_Student* s = new Student();
如何通过指针 s 调用方法而不使它们在 I_Student 中成为纯虚拟?
考虑:
-
Base
正在I_Student
-
Derived
正在Student
是的,您可以使用类型为 Base*
(实际上指向Derived
实例(调用Derived
类的方法。所以你总是可以投掷另一种方式。
#include <iostream>
class Base
{
public:
virtual void Foo() = 0;
virtual void Bar() = 0;
};
class Derived : public Base
{
public:
void Foo() { std::cout << "Foo is calledn"; }
void Bar() { std::cout << "Bar is calledn"; }
void FooBar() { std::cout << "FooBar is calledn"; }
};
int main()
{
// Example 1 (Assume that basePtr is pointing to a Derived instance)
{
Base* basePtr = new Derived;
static_cast<Derived*>(basePtr)->FooBar();
delete basePtr;
}
// Example 2 (Verify that basePtr is pointing to a Derived instance)
{
Base* basePtr = new Derived;
if (Derived* derived = dynamic_cast<Derived*>(basePtr))
{
derived->FooBar();
}
delete basePtr;
}
return 0;
}
从
I_Student*
访问派生类Student
的方法是不可能的,除非先强制转换为Student
。
Student* s2 = dynamic_cast<Student*>(s);
if (s2 != nullptr)
...
您可以通过类调用派生类或学生类的函数I_student
只需将函数设置为虚函数即可。一旦一个函数被虚拟化,现在每当它被调用时,它都会根据对象调用它的引用来调用。在这种情况下,指针 's' 的类型是 I_students
,但它具有其父级的引用。这就是调用学生函数的方式。我在这里展示了它
class I_Students
{
public:
virtual void print()
{
cout << "Im I_student"<<endl;
}
};
class Students :public I_Students
{
public:
virtual void print()
{
cout << "Im student" << endl;
}
};
int main()
{
I_Students *s = new Students;
s->print();
}
相关文章:
- 在 c++ 中,有一种方法可以创建一个包含地图作为值的树状地图?
- 在C++中包含原型文件的正确方法是什么?
- 在Visual Studio C++项目中包含源库的正确方法是什么?
- 将 c++ 包含添加到日食的正确方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 从内部类中的方法从包含类调用方法
- 使用包含互斥锁的类的方法实例化 cpp11 线程
- 生成包含给定类型的 N 个参数的可变参数列表的最佳方法?
- 在wxWidgets的事件中包含我自己的数据的最佳方法是什么?
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 在CMakeLists中包含目录的更好方法.txt
- 唯一 ptr 将所有权移动到包含对象的方法
- 在类中包含 zmq::socket_t 成员的正确方法?
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 避免遗漏包含相同文件的最佳方法是什么?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法
- 为什么C 容器没有包含方法
- 如果派生类只包含方法(没有成员变量),向下强制转换是否安全?
- 如何让本地匿名c++函数对象使用包含方法的参数