简体   繁体   English

可以使用非静态函数在c ++中修改静态变量

[英]Can Non-static function modify a static variable in c++

can非静态函数可以在c ++中修改静态变量

是的,只要数据成员的可见性允许,非静态成员函数就可以修改静态数据成员。

Yes, see this example for a small sample program. 是的,请参阅此示例以获取一个小型示例程序。

Conversely a static function cannot modify a regular member variable the way a regular member function can. 相反,静态函数不能像常规成员函数那样修改常规成员变量。

Yes you can. 是的你可以。

Think of "static members" as if they were attributes that characterize the class while "non-instance members" characterize instances. 将“静态成员”视为表征类的属性,而“非实例成员”表征实例。

Classes define a concept while instances are occurences of this concepts. 类定义了一个概念,而实例是这个概念的出现。 A silly example is the class Human is a concept while you, Andy, is an instance. 一个愚蠢的例子是Human是一个概念,而你,安迪,是一个实例。 You are one human among 6 billion others. 你是60亿人中的一个人。

Human concept says that all humans have limbs, head, eyes and so on. 人类的观念认为,所有人类都有肢体,头部,眼睛等。 Those are instance fields . 那些是实例字段 Every human instance has its own limbs, head, eyes... 每个人类都有自己的四肢,头部,眼睛......

I can specialize the human concept according to his/her profession. 我可以根据他/她的职业专门研究人类的概念。 Lets consider a ComputerEngineer class that defines, obviously, computer engineers. 让我们考虑一个ComputerEngineer类,它显然定义了计算机工程师。 Any instance of computer engineer is a human and still has limbs, head, eyes... 计算机工程师的任何实例都是人类,仍然有四肢,头部,眼睛......

The ComputerEngineer class, however, can be modeled so that it has a qualifier (or attribute) that says the minimum salary that the category sindicate allows. 但是,可以对ComputerEngineer类进行建模,使其具有一个限定符(或属性),该限定符表示类别sindicate允许的最低工资。 Lets call it minimumWage 让我们称之为minimumWage

This is a situation were the same attribute must have a common value for all the class instances. 这是一个情况,相同的属性必须具有所有类实例的公共值。

Note that although this minimumWage is not an instance member and cannot have different values for each instance, it is still related to the concept, so it is reasonable that it can be accessed. 请注意,虽然此minimumWage不是实例成员,并且不能为每个实例使用不同的值,但它仍然与概念相关,因此可以访问它是合理的。

The following fake code is valid in the sense of having an instance method accessing a static member: 以下假代码在访问静态成员的实例方法的意义上是有效的:

class Human
{
protected:
  Limb leftArm;
  Limb leftLeg;
  Limb rightArm;
  Limb rightLeg;
};

class ComputerEngineer : public Human
{
protected:
  static double _minimumWage;
  double _wage;

public:
  wage( double w )  // non-static member function can only be called by instances.
  {
    if ( w < minimumWage )
       throw "You're gonna have trouble with the union!";
    _wage = w;
  }

  minimumWage( double w )
  {  _minimumWage = w; }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM