基 class 中的虚方法和子 class 中的非虚方法。即使它是非虚拟的,子 class 方法仍然如何被调用
virtual method in base class and non virtula method in child class. Still how child class method is called even if its is non-virtual
我正在检查下面提到的一段代码,发现子 class 中的方法是非虚拟的,该方法仍然被其基 class 指针调用。谁能告诉我原因……?
class Base {
virtual void method() { std::cout << "from Base" << std::endl; }
public:
virtual ~Base() { method(); }
void baseMethod() { method(); }
};
class A : public Base {
void method() { std::cout << "from A" << std::endl; }
public:
~A() { method(); }
};
int main(void) {
Base* base = new A;
base->baseMethod();
getchar();
return 0;
}
输出 - 来自 A
派生 class 中覆盖虚方法的方法也将是 virtual;它与是否使用关键字 virtual
无关。
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
我正在检查下面提到的一段代码,发现子 class 中的方法是非虚拟的,该方法仍然被其基 class 指针调用。谁能告诉我原因……?
class Base {
virtual void method() { std::cout << "from Base" << std::endl; }
public:
virtual ~Base() { method(); }
void baseMethod() { method(); }
};
class A : public Base {
void method() { std::cout << "from A" << std::endl; }
public:
~A() { method(); }
};
int main(void) {
Base* base = new A;
base->baseMethod();
getchar();
return 0;
}
输出 - 来自 A
派生 class 中覆盖虚方法的方法也将是 virtual;它与是否使用关键字 virtual
无关。
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).