[英]Can type be created(or template instantiated) by object known at compile time?
[英]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.