문제

I do not know why but this code works, what does this record }r; and how it works ? can in this way be declared a global object class ?

#include <iostream>

class А
{
    public:
        А()
        {
            std::cout << "Hello World";
        }
}r;

int main()
{

}
도움이 되었습니까?

해결책

That declares a global variable named r that is of type A.

It's the same as

class A { ... };

A r;

int main() { ... }

다른 팁

can in this way be declared a global object class ?

Um, yeah! Basically, r there is a global variable of type А. C++ has inherited from C a certain syntax that enables you to declare variables after a class/struct definition. You can often see from C something like

struct vertex {
   float x, y;
} my_vertex; // Declares a variable of type vertex

In C++, a struct is the same as class with the exception of the default access specifier.

You might have wondered what the semicolon is for after class definitions. So basically a class defined as

class my_class {};

with the braces immediately proceeded by a semicolon declares no variables.

You can also declare more than one variables by delimiting them with the comma operator.

class my_class {} x, y, z;

It Create one instance of class A with name r. It's pretty much the same as doint int r; Which would make a global int on that position.

maybe this helps you for a better understanding.

C++: Declare a global class and access it from other classes?

br

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top