gpt4 book ai didi

c++ - 是否在类外重新声明一个 const 静态变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:00 25 4
gpt4 key购买 nike

在 C++ Primer 4th 12.6.2 中,建议在类外重新声明一个 const 静态变量。

但是,下面的代码在 gcc 4.6.3 中通过了。

#include <iostream>
using namespace std;

class X {
public:
const static int a = 1;
};

// const int X::a;

int main() {
X x;
cout << x.a << endl;
return 0;
}

我们应该重新声明它吗?

附言:

根据 Potatoswatter 的推荐,我添加了一个函数来使用 const static 成员作为引用:

const int X::a;

void test(const int& a) {
cout << a << endl;
}

int main() {
X x;
test(X::a);
return 0;
}

如果我们不在 X 类之外包含 const int X::a,则会产生如下错误

对“X::a”的 undefined reference

无论是否为 const static,在类外部进行定义都是一种很好的做法。

最佳答案

不,您不需要重新声明它,因为您已经在单行中声明和定义了它:

const static int a = 1;

但是,对于static数据成员(包括const static),如果你只在类中给出它的声明。您必须在类声明之外的命名空间范围内定义静态成员。 For example :

class X
{
public:
static int i; // declaration
};
int X::i = 0; // definition outside class declaration

关于c++ - 是否在类外重新声明一个 const 静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439848/

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