首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >定义常数静态数据成员

定义常数静态数据成员
EN

Stack Overflow用户
提问于 2018-04-30 22:26:56
回答 3查看 7.3K关注 0票数 9

因此,我知道在C++中,如果静态成员是const文本类型,则可以在类中初始化它们,如下所示

代码语言:javascript
运行
复制
class test{
public:
        static constexpr int stc = 1;
private:
        int a = 0;
        int b = 0;
        int c = 0;
};

在编译器可以直接替换成员值的情况下,可以使用静态stc变量,例如

代码语言:javascript
运行
复制
int main () {int array[test::stc];}  

但是,如果在编译器不能直接替换值的上下文中使用:

代码语言:javascript
运行
复制
int main() { const int &cs = test::stc; } 

然后编译器(clang)生成一个错误。

代码语言:javascript
运行
复制
c++ -std=c++11 -pedantic    t.cpp   -o t
Undefined symbols for architecture x86_64:
  "test::stc", referenced from:
      _main in t-a8ee2a.o
ld: symbol(s) not found for architecture x86_64

除非静态成员在类的外部定义,如下所示:

constexpr int test::stc;

为什么是这种情况?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-05-01 05:43:27

在……里面

代码语言:javascript
运行
复制
int main() { const int &cs = test::stc; } 

test::stc是odr-在

代码语言:javascript
运行
复制
int main () {int array[test::stc];}  

不是的。

来自C++11标准的以下示例支持上述思想。

结构S{ static x= 0;};const &f(const &r);int =b?(1,S:X) // S​::​x不是odr-在这里使用: f( S::x);// S-​::​x在这里使用,因此需要定义

从实际角度来看,cs将是一个无效的引用,除非test::stc有一个地址。另一方面,array只需要test::stc的值,它可以在编译时进行计算。array不需要test::stc的地址就能成为有效的对象。

odr使用的对象必须在程序中精确定义一次.

票数 6
EN

Stack Overflow用户

发布于 2018-05-01 00:17:35

代码语言:javascript
运行
复制
static constexpr int stc = 1; // declares the static var

constexpr int test::stc; // defines the static var

有关更详细的解释,请参阅下面的链接

http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

票数 2
EN

Stack Overflow用户

发布于 2019-08-08 10:21:35

inline变量C++17

在C++17中,如果您也将静态成员标记为inline,那么我相信您可以自由地使用它,或者跨编译单元具有多个定义,例如:

代码语言:javascript
运行
复制
#include <iostream>

class MyClass {
    public:
        inline static constexpr int i = 42;
};


int main() {
    const int &cs = MyClass::i;
    std::cout << cs << std::endl;
    std::cout << &MyClass::i << std::endl;
}

更多信息请访问:内联变量是如何工作的?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50109036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档