【问题标题】:What is the use of virtual class and abstract class in C++ [closed]C ++中虚拟类和抽象类的用途是什么[关闭]
【发布时间】:2014-02-26 10:06:57
【问题描述】:

我了解什么是虚函数和纯虚函数,但是,C++ 中虚函数的用途是什么。对于这个可以使用虚函数的概念,我能找到一个更恰当的例子吗?

为此给出的示例是 1.塑造一个基类 2.Rectangle和square是派生类

我的问题是首先需要形状派生类吗? 为什么我们不能直接使用 rectangle 和 square 类

【问题讨论】:

  • 这可能会有所帮助stackoverflow.com/questions/2391679/…
  • 请不要滥用标准术语。 “实时”在 IT 中具有非常特殊的含义,但事实并非如此。你的意思是类似于“真实世界”的东西。您需要查找“多态性”,这是 OOP 的支柱之一。
  • 解析来自网络的各种应用程序消息?

标签: c++ virtual-functions


【解决方案1】:

您可以使用虚函数来实现运行时多态性。

【讨论】:

  • 我们可以使用纯虚函数来制作接口。
【解决方案2】:

当您想要为派生类覆盖某种行为(读取方法)而不是为基类实现的行为时,您可以使用虚函数,并且您希望在运行时通过指向基类的指针来这样做。

例子:

#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.
}

输出将是:

Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多