简体   繁体   English

为什么编译器不为类内部声明的变量分配内存?

[英]Why does compiler not allocate memory to the variable declared inside class?

When we declare some variable inside class or struct in C/C++, we have to make an object of class or struct to allocate memory for the variable.当我们在 C/C++ 中在classstruct中声明某个变量时,我们必须创建一个classstruct的对象来为变量分配内存。

Why can't we just access these variables without any object?为什么我们不能在没有任何对象的情况下访问这些变量?

Well, the answer is really: because that's the whole point of this language feature.嗯,答案是真的:因为这就是该语言功能的全部意义所在。 The very idea of a data member of a class is for it to be an integral part of class object.数据成员的想法是让它成为类对象的一个​​组成部分。 It begins its life together with the entire class object and it ends its life together.它与整个类对象一起开始它的生命,并一起结束它的生命。

If you have two class objects, you have two completely independent sets of data members.如果您有两个类对象,则您有两个完全独立的数据成员集。 If you have 50 class objects, you have 50 completely independent sets of data members.如果你有 50 个类对象,你就有 50 组完全独立的数据成员。 If you have zero class objects, you have no sets of data members to access.如果您有零个类对象,则没有要访问的数据成员集。 In other words, you cannot access these "variables" without a class object simply because they do not exist without a class object.换句话说,你不能在没有类对象的情况下访问这些“变量”,因为它们在没有类对象的情况下不存在。

You are not really "declaring a variable" when you declaring a data member of a class in a class definition.当您在类定义中声明类的数据成员时,您并不是真正“声明变量”。 Class definition simply describes the layout of class type.类定义只是描述了类类型的布局。 By itself it produces nothing physical, ie noting that would live in data memory, noting you can physically access.它本身不会产生任何物理内容,即注意它会存在于数据存储器中,注意您可以物理访问。

Meanwhile, C++ language has such concept as static member of the class.同时,C++语言有类的静态成员这样的概念。 Static data members of the class are not associated with specific class objects.类的静态数据成员不与特定的类对象相关联。 They exist independently.它们独立存在。 In fact, static data members are just ordinary global variables covered by a fairly thin layer of C++-specific "syntactic sugar" (more elaborate naming, access control etc.) Static data members of the class can be accessed as ordinary variables, without any object.事实上,静态数据成员只是普通的全局变量,覆盖了一层相当薄的 C++ 特定的“语法糖”(更精细的命名、访问控制等)。类的静态数据成员可以作为普通变量访问,没有任何目的。

In other words, it is not a question of "why?"换句话说,这不是“为什么”的问题。 but rather a question of what you need.而是你需要什么的问题。 If you want non-static data member functionality, use non-static data members.如果您需要非静态数据成员功能,请使用非静态数据成员。 If you want static data member functionality... well, you get the idea.如果你想要静态数据成员功能......好吧,你明白了。

A class is just a 'layout' used to specify how instanced object will be constructed, destroyed and how they will behave.类只是一个“布局”,用于指定实例对象将如何构造、销毁以及它们将如何运行。 For an imaged comparizon with buildings: a class is the plan used to build the house.对于与建筑物的图像比较:类是用于建造房屋的计划。 The object is the house itself.对象是房子本身。

If you want variable without objects, use global variables.如果您想要没有对象的变量,请使用全局变量。 You can put them in a namespace:您可以将它们放在命名空间中:

namespace test
{
    int answer = 42; // Initialization is optional
}

// ...

void f()
{
    // Use it like this:
    test::answer = 0;
}

You can also use static members:您还可以使用静态成员:

class MyClass
{
    public:
        static int value;
};

Usually, you declare a member variable inside a class precisely because you want it to be part of an object of that class type.通常,您在类中声明成员变量正是因为您希望它成为该类类型对象的一部分。 That's what that language feature is for: to allow you to have many distinct objects, each with its own state independent of any other object.这就是该语言特性的用途:允许您拥有许多不同的对象,每个对象都有自己的状态,独立于任何其他对象。

In C++ (but not C), you can declare it static if you want a single variable, independent of any object.在 C++(但不是 C)中,如果您想要一个独立于任何对象的单个变量,您可以将其声明为static This will have static storage duration, just like a variable declared outside a class.这将具有静态存储持续时间,就像在类外声明的变量一样。 In C, global variables are the only option if you want something like this.在 C 中,如果你想要这样的东西,全局变量是唯一的选择。

For example:例如:

struct thing {
    int a;         // part of a "thing" object
    static int b;  // not part of a "thing"
};

// Static variables need a definition, in exactly one source file
int thing::b;

int main() {
    thing::b = 1; // OK: no object needed
    thing::a = 2; // ERROR: object needed

    thing t1;
    t1.a = 3;     // OK: accessing object member
    t1.b = 4;     // OK: equivalent to "thing::b"

    thing t2;
    t2.a = 5;     // OK: accessing object member
    t2.b = 6;     // OK: equivalent to "thing::b"

    std::cout << t1.a;  // prints 3
    std::cout << t2.a;  // prints 5 - independent of t1.a

    std::cout << t1.b;  // prints 6
    std::cout << t2.b;  // prints 6 - same variable as t1.b (aka thing::b)
}

Using the static keyword:使用静态关键字:

class A {
public:
    static int varaible;
};

int A::variable = 5;

Then you can access the variable without an object anytime.然后您可以随时访问没有对象的变量。 As follows.如下。

A::varaible = 25;

Things you'll need to know:你需要知道的事情:

  1. You will need to use the scope operator(::) to access a static member.您将需要使用作用域运算符 (::) 来访问静态成员。
  2. Definition of a static member must be done outside of the class.静态成员的定义必须在类之外完成。 The above statement int A::variable = 5;上面的语句int A::variable = 5; is an definition of a static member.是静态成员的定义。
  3. All objects of type A (included inherited objects) share a static member.所有类型A对象(包括继承的对象)共享一个静态成员。 [1] [1]

[1] [1]

A a;
A b;
a::variable == b::variable == 25;
//if we change a::variable
a::variable = 26;
//b::variable has the same value.
b::variable == a::variable == 26;

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

相关问题 派生类是否为成员变量分配内存? - Does derived class allocate memory for member variable? 为什么编译器会为此循环的每次迭代将成员变量写入内存? - Why does the compiler write a member variable to memory for each iteration of this loop? new()是否也为类的函数分配内存? - Does new() allocate memory for the functions of a class also? 文字值的范围是什么,编译器如何为其分配内存? - What is the scope of a literal value, and how does the compiler allocate memory to it? 为什么编译器为什么对我在上面的“ if”语句中声明的变量说“未声明的标识符”? - Why does the compiler say “undeclared identifier” for a variable I declared in the “if” statement just above? 为什么编译器会忽略模板类中的struct元素? - Why does the compiler ignore struct elements inside a template class? 编译器如何在堆栈上分配内存 - How Compiler allocate memory on stack C ++中的析构函数是否自动在类内部释放已声明的指针变量的内存? - Does destructor in C++ automatically deallocates memory of the declared pointer variables inside the class? 派生类的实例化是否为基类的私有成员分配内存? - Does an instantiation of a derived class allocate memory for private members of base class? 动态地为课程分配内存 - dynamiclly allocate memory for class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM