1

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

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

我不明白对象的类型在编译时可能是未知的。从源代码中不是很明显吗?

4

3 回答 3

1

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 的答案,它使用引用(这是另一种持有对象句柄的方法)。

于 2013-08-23T03:16:11.260 回答
1

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

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,无法知道它应该调用哪个函数。事实上,它每次都需要调用不同的函数。第一次调用 with 时f(b),需要调用B::f(),第二次调用 withf(c)时,需要调用C::f()

于 2013-08-23T03:21:05.233 回答
0

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

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.
于 2013-08-23T03:25:34.680 回答