查询C ++中的类的静态成员变量 [英] Query on Static member variables of a class in C++

查看:137
本文介绍了查询C ++中的类的静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在C ++代码中有以下内容:

  class Foo 
{
public:
static int bands;
...
...
private:
...
...

} //类定义结束

int Foo :: bands; //注意:这里没有初始化任何值!




    <


  1. 也可以将静态变量声明为任何类中的私有成员变量。



解决方案

C ++注意到声明频段在类中声明,但未定义。



定义该类型的对象,但由于静态成员不是任何一个特定对象的一部分,它需要它自己的定义。


Sorry if this question seems trivial to many here.

In a C++ code there is something as below:

class Foo
{
public:
   static int bands;
   ...
   ...
private:
   ...
   ...

}//class definition ends

int Foo::bands; //Note: here its not initialized to any value!

  1. Why is the above statement needed again when 'bands' is once declared inside the class as static?

  2. Also can a static variable be declared as a private member variable in any class?

解决方案

C++ notes a distinction between declaring and defining. bands is declared within the class, but not defined.

A non-static data member would be defined when you define an object of that type, but since a static member is not a part of any one specific object, it needs it's own definition.

这篇关于查询C ++中的类的静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆