我不知道如何問這個,但基本上我將基類作為引數傳遞,如果引數是基類的派生類,我希望只能訪問派生類中的屬性
class A{
public:
bool isB = false;
int x = 69;
}
class B : public A{
public:
bool isB = true;
int y = 420;
}
void Print(A c){
if (c.isB)
cout << c.y << endl; //this will error as the class A has no y even though i will pass class B as an argument
else
cout << c.x << endl;
}
A a;
B b;
Print(a);
Print(b);
uj5u.com熱心網友回復:
我的建議是您通過創建一個全域函式呼叫的虛擬“列印”函式來使用多型性Print:
class A
{
int x = 69;
public:
virtual ~A() = default; // Needed for polymorphic classes
virtual void print(std::ostream& out) const
{
out << x;
}
};
class B : public A
{
int y = 420;
public:
void print(std::ostream& out) const override
{
out << y;
}
};
void Print(A const& o)
{
o.print(std::cout);
std::cout << std::endl;
}
int main()
{
A a;
B b;
Print(a);
Print(b);
}
uj5u.com熱心網友回復:
您需要在基類和派生類中定義一個回傳“isB”的虛函式“bool amIaB()”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371199.html
上一篇:物件編程問題
下一篇:類繼承代碼中的意外輸出
