声明为私有时的静态成员变量 [英] static member variable when declared private

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

问题描述

当静态成员变量在类中声明为私有时,如何定义它?

When a static member variable is declared private in a class, how can it be defined?

假设我有以下类声明

class static_demo
{
   private:
      static int a;

   public:
      static int b;

      void set(int x, int y)
      {
         a = x;
         b = y;
      }

      void show()
      {
         cout << "a = " << a << "\n";
         cout << "b = " << b << "\n";
      }
};

然后下面的语句来定义 a

Then the following statement to define a will result in compilation error.

int static_demo::a;

那么在类的私有部分中可以有一个静态数据成员吗?

So is it possible to have a static data member in the private section of class?

按照Greg添加完整代码

#include <iostream>

using namespace std;

class static_demo
{
   private:
      static int a;

   public:
      static int b;

      void set(int x, int y)
      {
         a = x;
         b = y;
      }
};

int static_demo::a;
int static_demo::b;

int main()
{
   static_demo::b = 10;
   static_demo::a = 20;

   return 0;
}

编译错误为:

static_member_variable.cpp: In function `int main()':
static_member_variable.cpp:20: error: `int static_demo::a' is private
static_member_variable.cpp:26: error: within this context


推荐答案


当静态成员变量在类中声明为私有时,如何定义它?

When a static member variable is declared private in a class, how can it be defined?

在与在source(cpp)文件中定义公共静态变量的方式相同。

In the very same way as you define a public static variable in your source(cpp) file.


int static_demo :: a = 1;

int static_demo::a = 1;

访问说明符在定义成员时不会给您错误。访问说明符控制成员变量的访问,定义一个静态变量是可以的。

Access specifiers will not give you error while defining the member. Access specifiers control the access of the member variables, defining a static variable is an excpetion which is allowed.

在Ideone上干净地编译 此处

Compiles cleanly on Ideone here.

编辑:发布代码后回答您的问题。

您的问题不是静态成员的定义。该错误是因为您试图访问 main 内部的私有静态成员。你不能这样做。

To answer your Q after you posted code.
Your problem is not the definition of the static member. The error is because you are trying to access the private static member inside main. You cannot do that.

只能在类成员函数内部访问类的私有成员,相同的规则甚至适用于静态成员。为了能够修改/访问静态成员,您必须在类中添加一个成员函数,然后在其内部修改/访问静态成员。

Private members of a class can only be accessed inside the class member functions, the same rule applies even to static members. To be able to modify/access your static members you will have to add a member function to your class and then modify/access the static member inside it.

这篇关于声明为私有时的静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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