Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

绿色网站无广告
会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > C/C PLUSPLUS > » 正文

What’s the difference between a class variable and an insta

来源: clark1231 分享至:

What’s the difference between a class variable and an instance variable?

Knowing the terminology is important. Instance variables and class variables are both member variables. They are both member variables because they are both associated with aspecificclass. But, there are differences between instance variables and class variables.

Instance variables

Instance variables belong to an instance of a class. Another way of saying that is instance variables belong to an object, since an object is an instance of a class. Every object has it’s own copy of the instance variables. Here is what a declaration of an instance variable would look like:

Example of an instance variable:

class Taxes
{
  int count;
  /*...*/
}

Class variables – also known as static member variables

Class variables, however, only haveonecopy of the variable(s) shared with all instances of the class. It’s important to remember thatclass variables are also known as static member variablesin C++, Java, and C#. Each object of the class does not have its own copy of a class variable. Instead, every object shares theone and onlycopy of that class variable – and any changes made to that copy are seen by all of the objects of that class. Here is what a class variable – or a static member variable – would look like in C++:

Example of a class variable:

class Taxes
{
  static int count;
  /*...*/
}

Difference between class and instance variables

Now, it should be clear what the difference between instance and class variables is. Class variables only have one copy that is shared by all the different objects of a class, whereas every object has it’s own personal copy of an instance variable. So, instance variables across different objects can have different values whereas class variables across different objects can have only one value.

Class and Instance variables are both Member variables

Here’s a little diagram to help you remember the differences between instance and class variables:


Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史