【问题标题】:Static type class in relation to pointers in C++与 C++ 中的指针相关的静态类型类
【发布时间】: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


【解决方案1】:

没有静态或动态的指针。 但是有静态和动态的类型


通常变量和表达式只有一种类型,也称为静态类型
多态类实例还具有动态类型

如果表达式引用位于派生类实例内部的基类实例,则表达式的动态类型就是派生类。


一个例子应该清楚地说明这一点:

Account *a = new Account(); 
Account *b = new Current();
Account *c = new Deposit();

这里 *a*b*c 都具有相同的静态类型 - Account。静态类型不依赖于这些指针指向的内容,只依赖于它们的声明方式。

另一方面,*a*b*c 的动态类型分别为 AccountCurrentDeposit。动态类型取决于指针实际指向的内容。

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 2016-12-15
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多