【发布时间】:2019-04-08 02:30:07
【问题描述】:
我对 C++ 中的静态和动态类型感到非常困惑。在下面的示例中,为什么 Account 指针被认为是静态的?
class Account{
public:
virtual string getType() { return "Generic Account"; };
};
class Current: public Account{
public:
virtual string getType() { return "Current Account"; };
};
class Deposit: public Account{
public:
virtual string getType() { return "Deposit Account"; };
};
int main()
{
// Note that all pointers have the static type Account
Account *a = new Account();
Account *b = new Current();
Account *c = new Deposit();
cout << "Pointer a Displayed: " << a->getType() << endl;
cout << "Pointer b Displayed: " << b->getType() << endl;
cout << "Pointer c Displayed: " << c->getType() << endl;
}
所有基类类型的指针都是静态的,而派生类的所有指针都是动态的吗?例如,将
当前 *d = new Deposit();
是动态的,因为它是派生类类型?提前致谢。
【问题讨论】:
-
您使用了不常用的术语。 “静态”和“动态”指针是什么意思?
-
C++ 是一种静态类型语言。如果您正在寻找动态类型语言,请查看 Python 之类的语言。一个指针只有一种类型,而且只有一种类型。
-
@MatthieuBrucher 指针确实只有一种类型。另一方面,多态类实例除了静态类型之外还有动态类型。
-
@HolyBlackCat 我知道...
标签: c++ pointers dynamic static overriding