我想在重新解釋的類中從父函式呼叫子函式,如下所示。
例子
#include <iostream>
class A {
public:
void func1() {
// some code
func2();
// some code
}
protected:
virtual void func2() {
printf("class A\n");
}
};
class B : public A {
protected:
virtual void func2() {
printf("class B\n");
}
};
int main() {
A* ab = new A();
ab->func1(); // this print "class A"
B* bab = reinterpret_cast<B*>(ab);
bab->func1(); // this also print "class A"
// I want to print "class B" when I use bab->func1()
}
在這種情況下,有沒有辦法在bab不重新定義的情況下使用重新解釋的類列印 B 類func1?
uj5u.com熱心網友回復:
要啟動 C 多型性,您必須在某處創建派生類的實體,但您可以存盤指向基類的指標。使用基類指標將分派到派生類的重寫函式。所以你對Aand的定義B很好,你在 main 函式中的用法不是。reinterpret_cast不適用于此。
#include <iostream>
#include <memory>
class A {
public:
void func1() {
// some code
func2();
// some code
}
protected:
virtual void func2() {
printf("class A\n");
}
};
class B : public A {
protected:
virtual void func2() {
printf("class B\n");
}
};
int main() {
{
// This works, but don't do this. Naked "new" is not modern C and dangerous.
A* ab = new B();
ab->func1();
delete ab;
}
{
// VARIANT 2: use smart pointers
std::unique_ptr<A> ab = std::make_unique<B>();
ab->func1();
}
{
// VARIANT 3: A non-smart pointer is okay, as long as it
// 1. references an existing allocated object
// 2. the pointer does not outlive the object it points to
B b;
A* ab = &b;
ab->func1();
}
{
// VARIANT 4: Like Variant 3, but with reference instead of pointer
B b;
A& ab = b;
ab.func1();
}
}
輸出
class B
class B
class B
class B
https://godbolt.org/z/8e5E85nx5
編輯:盡量避免使用new. 以這種方式分配的任何記憶體都必須由您使用釋放,delete而且很容易忘記(我第一次寫這個答案時就忘記了,有點證明我的觀點)。即使您確實洗掉了函式末尾的記憶體,您的代碼也有可能永遠不會到達此陳述句,例如,如果在 和 之間的某處拋出例外。new這里delete有一些進一步的閱讀:
- 為什么使用“new”是個壞主意?
- 為什么 C 程式員應盡量減少使用“new”?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/534946.html
標籤:C 遗产
上一篇:建構式什么時候被子類繼承
