Home  >  Q&A  >  body text

c++ - 类的静态成员存在于任何对象之外,对象中不包含任何与静态数据成员有关的数据?

书上看到这句话,我觉得明显写错了,大家怎么看?
比如calculate()就包含interestRate成员

天蓬老师天蓬老师2765 days ago652

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 12:11:10

    The book is correct. What the book means is not that objects of a class cannot access static members of the class, but that no static members of the class will be stored in the object. When an object needs to access static members, it first finds the class itself, and then accesses the static members in it.

    So in your example, owner and amount exist in objects, while interestRate exists in classes. When accessing this static variable, you need to find the class first and then find the variable.

    Because static members of a class are shared by all objects, if they are stored in each object, when one object modifies the variable, other objects will not be able to see the modified result. This is consistent with the characteristics of static members. is inconsistent.

    reply
    0
  • Cancelreply