gpt4 book ai didi

c++ - 具有全局成员歧义的静态数据成员定义

转载 作者:行者123 更新时间:2023-11-27 22:51:19 26 4
gpt4 key购买 nike

在定义类的静态成员时,当x既是全局变量又是类中的静态变量时,会出现如下歧义。

ambiguity.cpp
using namespace std;

int z = 100;

int x = 100;

class WithStatic {

static int x;
static int y;
static int a;

public:

void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
cout << "WithStatic::a = " << a << endl;
}
};

int WithStatic::x = 1;
int WithStatic::y = x + 1;
int WithStatic::a= z+1;

int main() {
WithStatic ws;
ws.print();
}

输出:

WithStatic::x = 1

WithStatic::y = 2

WithStatic::a = 101

我在定义 y 时遇到问题。为什么不采用全局 x 呢? WithStatic::x 被采用。为什么 y 的输出不等于 101 而不是 2?

最佳答案

来自 n4567

9.4 静态成员[class.static]

第 3 段:

A static member may be referred to directly in the scope of its class or in the scope of a class derived (Clause 10) from its class; in this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.

// Example:
int g();
struct X
{
static int g();
};
struct Y : X
{
static int i;
};
int Y::i = g(); // equivalent to Y::g();

关于c++ - 具有全局成员歧义的静态数据成员定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com