[英]In C++ if a member function is virtual when can static binding be used?
In C++ when can a virtual function use static binding? 在C ++中什么时候虚函数可以使用静态绑定? If it is being accessed through a pointer, accessed directly, or never?
如果通过指针访问它,直接访问,或从不?
When a virtual method is called through a pointer or reference, dynamic binding is used. 通过指针或引用调用虚方法时,将使用动态绑定。 Any other time, compile-time binding is used.
在任何其他时间,使用编译时绑定。 Ex:
例如:
class C;
void Foo(C* a, C& b, C c) {
a->foo(); // dynamic
b.foo(); // dynamic
c.foo(); // static (compile-time)
}
If you want to call the base class version of a function, you can do that by explicitly naming the base class: 如果要调用函数的基类版本,可以通过显式命名基类来实现:
class Base
{
public:
virtual ~Base() {}
virtual void DoIt() { printf("In Base::DoIt()\n"); }
};
class Derived : public Base
{
public:
virtual void DoIt() { printf("In Derived::DoIt()\n"); }
};
Base *basePtr = new Derived;
basePtr->DoIt(); // Calls Derived::DoIt() through virtual function call
basePtr->Base::DoIt(); // Explicitly calls Base::DoIt() using normal function call
delete basePtr;
Static binding can only be done when the object's type is totally unambiguous at compile time. 静态绑定只能在对象的类型在编译时完全明确时才能完成。 I can only think of four places where an abstract object's type is unambiguous: in the constructor, in the destructor, when declared locally and within the same scope as a dynamic allocation.
我只能想到抽象对象的类型是明确的四个地方:在构造函数中,在析构函数中,当在本地声明时,在与动态分配相同的范围内。 I don't know the standard that well so I couldn't say what it says about those four possibilities (I'd say the first two are statically bound, the third possible statically bound and the last not; although it probably says it's undefined or implementation dependent).
我不太清楚这个标准,所以我不能说它对这四种可能性的说法(我说前两个是静态绑定的,第三个可能是静态绑定而最后一个不是;虽然它可能说它是未定义的或实施依赖)。 Other than those points, the object being accessed through a base class pointer could be pointing to a derived class and the current translation unit has no way of knowing, so static binding is not possible.
除了这些点之外,通过基类指针访问的对象可能指向派生类,而当前的翻译单元无法知道,因此静态绑定是不可能的。 The function could be called with a pointer to the base class in one instance and a pointer to a derived class in another!
可以使用指向一个实例中的基类的指针和指向另一个实例中的派生类的指针来调用该函数!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.