简体   繁体   English

在编译时如何未知对象类型?

[英]How can an object type be unknown at compile time?

I am currently learning about dynamic binding and virtual functions. 我目前正在学习动态绑定和虚拟功能。 This is from Accelerated C++, chapter 13: 摘自Accelerated C ++第13章:

[...] We want to make that decision at run time. [...]我们想在运行时做出决定。 That is, we want the system to run the right function based on the actual type of the objects passed to the function, which is known only at run time. 也就是说,我们希望系统根据传递给函数的对象的实际类型来运行正确的函数,这仅在运行时才知道。

I don't understand the very idea that the type of an object can be unknown at compile time. 我不明白在编译时对象类型可能是未知的想法。 Isn't it obvious from the source code? 从源代码中不明显吗?

C++ has a concept of pointers , where the variable holds only a "handle" to an actual object. C ++具有指针的概念,其中变量仅包含指向实际对象的“句柄”。 The type of the actual object is not known at compile-time, only at runtime. 实际对象的类型在编译时未知,仅在运行时未知。 Example: 例:

#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!"
}

See also: Vaughn Cato's answer, which uses references (which is another way to hold a handle to an object). 另请参阅:Vaughn Cato的答案,该答案使用引用 (这是持有对象句柄的另一种方式)。

Not at all. 一点也不。 Consider this example: 考虑以下示例:

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);
}

When the global function f is compiled, there is no way to know which function it should call. 编译全局函数f ,无法知道应该调用哪个函数。 In fact, it will need to call different functions each time. 实际上,它每次都需要调用不同的函数。 The first time it is called with f(b) , it will need to call B::f() , and the second time it is called with f(c) it will need to call C::f() . 第一次使用f(b)调用,它将需要调用B::f() ,第二次使用f(c)调用,它将需要调用C::f()

Say you have a pointer to base class pointing to a derived object 假设您有一个指向基类的指针,该指针指向派生对象

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM