簡體   English   中英

在編譯時如何未知對象類型?

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

我目前正在學習動態綁定和虛擬功能。 摘自Accelerated C ++第13章:

[...]我們想在運行時做出決定。 也就是說,我們希望系統根據傳遞給函數的對象的實際類型來運行正確的函數,這僅在運行時才知道。

我不明白在編譯時對象類型可能是未知的想法。 從源代碼中不明顯嗎?

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的答案,該答案使用引用 (這是持有對象句柄的另一種方式)。

一點也不。 考慮以下示例:

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()

假設您有一個指向基類的指針,該指針指向派生對象

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