Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 创建多个实例后,静态数据成员的值是多少?_C++ - Fatal编程技术网

C++ 创建多个实例后,静态数据成员的值是多少?

C++ 创建多个实例后,静态数据成员的值是多少?,c++,C++,我的问题是:创建多个实例后,静态数据成员的值是多少??? 如果我有C++的代码: class car { public: static int x; car() { x=x+1; } } void main() { car first=new car();// here the value of x is 1; car tow=new car();// here the value of x is 2; int y

我的问题是:创建多个实例后,静态数据成员的值是多少??? 如果我有C++的代码:

class car
{
    public:
    static int x;
    car()
    {
        x=x+1;
    }
}

void main()
{
    car first=new car();// here the value of x is 1;
    car tow=new car();// here the value of x is 2;
    int y=first.x; // here what the value of y
}

y的值是1或2???

您的代码基本上是错误的,但要回答您的问题,是的,静态类成员的要点是它们由该类的每个实例共享

因此,如果将x设置为类car的静态成员,那么每次调用递增x的car构造函数时,x的值将增加1。

y的值将为2。 下面是我如何在Visual Studio中使用它的:

#include "stdafx.h"
#include <iostream>

class car
{
public:
    static int x;
    car();
};

int car::x = 0;

car::car(){
    x = x + 1;
}

int main()
{
    car first = car();// here the value of x is 1;
    car tow = car();// here the value of x is 2;
    int y = first.x; // here what the value of y

    std::cout << y;

    int wait;
    std::cin >> wait;
}
#包括“stdafx.h”
#包括
班车
{
公众:
静态int x;
car();
};
int car::x=0;
汽车{
x=x+1;
}
int main()
{
car first=car();//这里x的值是1;
car tow=car();//这里x的值是2;
int y=first.x;//这里y的值是多少
std::cout>等待;
}

好吧,你可以很容易地尝试一下。但是你不能,因为有4次出现3种不同的错误会阻止它编译。所以y的值是2@佐比达