静态成员变量在c ++中的本地类内? [英] static member variable inside a local class in c++?

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

问题描述

我知道我们不能在本地类中声明一个静态成员变量...
,但原因不清楚。

I know we cannot declare a static member variable inside a local class... but the reason for it is not clear.

任何人解释它?

此外,为什么我们不能访问非静态变量define在函数内,其中已定义了本地类,直接在本地类成员函数?

Also, why can't we access a non-static variable define inside the function, within which the local class has been defined,directly in the local class member functions?

在下面的代码中:

int main(int argc, char *argv[])
{
    static size_t staticValue = 0;

    class Local
    {
         int d_argc; // non-static data members OK
         public:
         enum // enums OK
         {
             value = 5
         };
         Local(int argc) // constructors and member functions OK
         : // in-class implementation required
          d_argc(argc)
         {
               // global data: accessible
               cout << "Local constructor\n";
               // static function variables: accessible
               staticValue += 5;
         }
         static void hello() // static member functions: OK
         { 
            cout << "hello world\n";
         }
   };
   Local::hello(); // call Local static member
   Local loc(argc); // define object of a local class.
   return 0;
}

静态变量staticValue是可直接访问的,而另一方面argc参数从main不是....

Static variable staticValue is directly accessible while on the other hand argc argument from main is not....

推荐答案

这两个问题是相关的。我相信答案不清楚,因为C ++中的 static 关键字具有重载的含义。

The two questions are related. I believe the answer is not clear to you because the static keyword in C++ has overloaded meanings.

在函数内部的静态变量,你真的告诉编译器只在第一次调用中初始化它(所以你可以使用多个调用的值)。这与文件范围或类范围的静态变量的情况不完全相同。

When you define a static variable inside the function, you're really telling the compiler to initialize it only in the first call (so you can use the value across multiple calls). This is not exactly the same of the case of a file-scope or class-scope static variable.

考虑到这一点,定义静态变量可能没有意义

With this in mind it might not make sense to define a static variable inside a local class, which is in turn defined inside a function.

关于第二个问题,一个本地类实际上可以访问在其封闭函数中定义的静态变量。例如,下面的代码应该在符合标准的编译器中编译。

Regarding your second question, a local class actually can access static variables defined in its enclosing function. The code below, for example, should compile in a standards-compliant compiler.


void f()
{
  static int i;
  class local
  {
    int g() { return i; }
  };

  local l;
  /* ... */
}

int main()
{
  f();
  return 0;
}

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

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