虚拟类和抽象类在C++; 我理解了虚函数和纯虚函数,但是C++中虚函数的用法是什么?对于这个概念,我能不能举一个更合适的例子,其中可以使用虚拟函数
给出的例子是 1.塑造基类 2.矩形和正方形是派生类 我的问题是,首先需要什么形状派生类?虚拟类和抽象类在C++; 我理解了虚函数和纯虚函数,但是C++中虚函数的用法是什么?对于这个概念,我能不能举一个更合适的例子,其中可以使用虚拟函数,c++,virtual-functions,C++,Virtual Functions,给出的例子是 1.塑造基类 2.矩形和正方形是派生类 我的问题是,首先需要什么形状派生类? 为什么我们不能直接使用矩形和方形类呢?当您希望重写派生类的特定行为(读取方法)而不是为基类实现的行为,并且希望在运行时通过指向基类的指针这样做时,您可以使用虚函数 例如: #include <iostream> using namespace std; class Base { public: virtual void NameOf(); // Virtual function.
为什么我们不能直接使用矩形和方形类呢?当您希望重写派生类的特定行为(读取方法)而不是为基类实现的行为,并且希望在运行时通过指向基类的指针这样做时,您可以使用虚函数 例如:
#include <iostream>
using namespace std;
class Base {
public:
virtual void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Base::NameOf() {
cout << "Base::NameOf\n";
}
void Base::InvokingClass() {
cout << "Invoked by Base\n";
}
class Derived : public Base {
public:
void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Derived::NameOf() {
cout << "Derived::NameOf\n";
}
void Derived::InvokingClass() {
cout << "Invoked by Derived\n";
}
int main() {
// Declare an object of type Derived.
Derived aDerived;
// Declare two pointers, one of type Derived * and the other
// of type Base *, and initialize them to point to aDerived.
Derived *pDerived = &aDerived;
Base *pBase = &aDerived;
// Call the functions.
pBase->NameOf(); // Call virtual function.
pBase->InvokingClass(); // Call nonvirtual function.
pDerived->NameOf(); // Call virtual function.
pDerived->InvokingClass(); // Call nonvirtual function.
}
您可以使用虚拟函数实现运行时多态性。这可能会有帮助,请不要误用标准术语。”“实时”在其中有一个非常具体的含义,但事实并非如此。你的意思是“真实世界”。您需要查找“多态性”,这是OOP的支柱之一。解析来自网络的一组不同的应用程序消息?我们可以使用纯虚拟函数来制作接口。
Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived