简体   繁体   English

C++ 中 main() 函数中声明的类

[英]Declared class inside the main() function in C++

In the following program, I have declared class inside the main() function.在下面的程序中,我在 main() 函数中声明了类。

case 1:情况1:

int main()
{
        static int i = 10; // static variable

        class A
        {
        public:
                A()
                {
                    std::cout<<i;
                }
        };
        A a;
        return 0;
}

and It's working fine in G++ compiler.它在G++编译器中运行良好。

But, If I remove static keyword and compile it, compiler gives an error.但是,如果我删除static关键字并编译它,编译器会出错。

Case 2:案例2:

int main()
{
        int i = 10; // removed static keyword

        class A
        {
        public:
                A()
                {
                    std::cout<<i;
                }
        };
        A a;
        return 0;
}

Error:错误:

 In constructor 'main()::A::A()':
13:32: error: use of local variable with automatic storage from containing function
:cout<<i;
                                ^
7:13: note: 'int i' declared here
         int i = 10;
             ^

Why case 1 working fine?为什么案例 1 工作正常? and Why doesn't working case 2?和为什么不工作案例 2?

Why doesn't it work?为什么不起作用?

Copy/paste from https://www.quora.com/Why-cant-local-class-access-non-static-variables-of-enclosing-functionhttps://www.quora.com/Why-cant-local-class-access-non-static-variables-of-enclosure-function复制/粘贴

You are wondering about a variable outside of a class.您想知道类之外的变量。 I will explain this the none-C++ way.我将用非 C++ 的方式解释这一点。 Let's look at it from the paradigm of general machine architecture and the way programming languages are oft defined.让我们从通用机器架构的范式和编程语言的定义方式来看。 The issue is stack frames, the concept of the stack, and how program refer to memory locations.问题是堆栈帧、堆栈的概念以及程序如何引用内存位置。

When a function is called, the variables of that function are pushed onto the stack.当一个函数被调用时,该函数的变量被压入堆栈。 A function and its variables are often a sequence of memory locations.函数及其变量通常是一系列内存位置。 When the function is finished, it and those variables are popped off the stack.当函数完成时,它和那些变量从堆栈中弹出。 That means when the function is called, variables come into existence.这意味着当函数被调用时,变量就存在了。 When the function is done, the variables depart immediately.函数完成后,变量立即离开。 Each variable, like the function itself are memory locations (may be assigned to registers).每个变量,就像函数本身一样,都是内存位置(可以分配给寄存器)。

Declaring the class does not declare a variable.声明类并不声明变量。 The class is just a definition in the world of C++ and has no linkage to the variable defined in the outer scope.类只是 C++ 世界中的一个定义,与外部作用域中定义的变量没有联系。 The phrase, automatic storage duration, is roughly synonymous with the idea of the variable (memory) automatically recovered when the function exits.短语自动存储持续时间与函数退出时自动恢复的变量(内存)的想法大致相同。 Even though it is C++, when it compiles, it is still machine language and will obey the rules of the machine.即使是C++,在编译的时候,仍然是机器语言,会遵守机器的规则。 The method you called on the class is part of the class but is not part of the function.您在类上调用的方法是类的一部分,但不是函数的一部分。 Only the class definition is local to the function.只有类定义是函数本地的。

All functions, regardless of where they exist are their own stack frame.所有函数,无论它们存在于何处,都是它们自己的堆栈帧。 The standard way stack frames are done means, unless the memory location referenced is valid, the data will be inaccessible by the time the function in the class is called.堆栈帧完成的标准方式意味着,除非引用的内存位置有效,否则在调用类中的函数时将无法访问数据。 In this case, it isn't because the variable in the outer scope has been reclaimed, but because when the method in the class is called, the stack frame in which the outer variable exists is not active in the series of registers used by the method being called.在这种情况下,并不是因为外层作用域中的变量被回收了,而是因为在调用类中的方法时,外层变量所在的栈帧在该类所使用的一系列寄存器中是不活动的。方法被调用。 The compiler was encoded with the understanding of this process and gave an error message to ward off the trouble that would ensue if such access was attempted.编译器在理解此过程的情况下进行编码,并给出错误消息以防止尝试此类访问时会出现的麻烦。

You can still access the variable if you affix the static keyword to the variable.如果将 static 关键字附加到变量,您仍然可以访问该变量。 That is mentioned in the web page Local Classes in C++ that has the same code example you have listed.在 C++ 中的本地类网页中提到了这一点,该网页与您列出的代码示例相同。 Basically, you have to extend the storage duration or the duration that the memory for the variable remains valid in the enclosing scope.基本上,您必须延长存储持续时间或变量内存在封闭范围内保持有效的持续时间。 Generally, a good way to think through these kind of error messages is through knowledge of the language specification, but in terms of time, relating the representations back to machine architecture can zero in on the underlying reasons why.一般来说,考虑这些错误消息的一个好方法是通过语言规范的知识,但就时间而言,将表示与机器架构联系起来可以归零根本原因。

How to work around it?如何解决它?

Simply pass the variable you'd like to use inside of the class as an argument to the constructor (i've made it a reference member, so changes in i will be visible inside of the class as well, but be aware that as soon as the function exits, i will go out of scope):只需将您想在类内部使用的变量作为参数传递给构造函数(我已将其设为引用成员,因此i更改也将在类内部可见,但请注意,尽快当函数退出时, i将超出范围):

#include<iostream>

int main()
{
  int i = 10; // static variable

  class A
  {
  private:
    int &r_i;
  public:
    A(int &i)
    :
      r_i(i)
    {
      std::cout<<r_i;
    }
  };
  A a(i);
  return 0;
}

如果我错了,我不确定请纠正我,这可能是因为静态变量和类都存储在堆中,因此情况 1 工作正常,而在情况 2 中,由于变量 i 未存储在堆中,因此会产生问题。

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

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