对象类型在编译时怎么可能是未知的

How can an object type be unknown at compile time?

本文关键字:未知 怎么可能 类型 编译 对象      更新时间:2023-10-16

我目前正在学习动态绑定和虚拟函数。这来自Accelerated C++,第13章:

[…]我们希望在运行时做出决定。也就是说,我们想要系统根据实际类型运行正确的功能传递给函数的对象,只有在运行时才知道。

我不理解在编译时对象的类型可能是未知的。从源代码来看,这不是很明显吗?

一点也不。考虑这个例子:

struct A {
  virtual void f() = 0;
};
struct B : A {
  virtual void f() { std::cerr << "In B::f()n"; }
};
struct C : A {
  virtual void f() { std::cerr << "In C::f()n"; }
};
static void f(A &a)
{
  a.f(); // How do we know which function to call at compile time?
}
int main(int,char**)
{
  B b;
  C c;
  f(b);
  f(c);
}

当编译全局函数f时,无法知道它应该调用哪个函数。事实上,它每次都需要调用不同的函数。第一次用f(b)调用它时,需要调用B::f(),第二次用f(c)调用它时需要调用C::f()

C++有一个指针的概念,其中变量只包含一个指向实际对象的"句柄"。实际对象的类型在编译时是未知的,只有在运行时才知道。示例:

#include <iostream>
#include <memory>
class Greeter {
public:
    virtual void greet() = 0;
};
class HelloWorld : public Greeter {
public:
    void greet() {std::cout << "Hello, world!n";}
};
class GoodbyeWorld : public Greeter {
public:
    void greet() {std::cout << "Goodbye, world!n";}
};
int main() {
    std::unique_ptr<Greeter> greeter(new HelloWorld);
    greeter->greet();    // prints "Hello, world!"
    greeter.reset(new GoodbyeWorld);
    greeter->greet();    // prints "Goodbye, world!"
}

另请参阅:Vaughn Cato的答案,它使用引用(这是保持对象句柄的另一种方式)。

假设您有一个指向基类的指针,指向派生对象

Base *pBase = new Derived;
// During compilation time, compiler looks for the method CallMe() in base class
// if defined in class Base, compiler is happy, no error
// But when you run it, the method call gets dynamically mapped to Derived::CallMe()
// ** provided CallMe() is virtual method in Base and derived class overrides it.
pBase->CallMe(); // the actual object type is known only during run-time.