【问题标题】:Initialize class variable float array in C++在 C++ 中初始化类变量浮点数组
【发布时间】:2019-03-27 21:20:07
【问题描述】:

我正在尝试初始化一个类变量数组。据我了解,正常的类变量初始化是这样的:

class test
{
public:
    static const float f;
};

但是,作为一个数组,突然不行了:

class test
{
public:
    static const float f[2];
};
//const float test::f = { 1 ,2};

整个代码应该可以工作,但是我注释掉了第 6 行。在第 4 行,它仍然抛出了

错误 LNK2001 未解析的外部符号“public: static float const * 常量测试::f"

我尝试了指针和动态分配,但两者都不起作用。怎么解决这个错误,第 6 行有什么问题吗?

【问题讨论】:

  • 您好像忘记了尺寸。试试const float test::f[2] = {1 , 2};
  • 首先,变量 F 是 const ,表示不能做 f[0] = value 或 f[1] = value ,它是只读变量,所以必须初始化首先,其次,您不能访问像 const float test::f = {1,2} 这样的类 obj 变量,而只能访问 test::{1,2};

标签: c++ arrays class


【解决方案1】:

说明

static test::f 表示f 未绑定到test 类实例。换句话说,只有一个f,就像testnamespace,而不是classf 只有一个,也正是一个。

注意

另外,您忘记添加必须在编译时提供的 f 数组的大小。 您还可以始终使用 decltype 说明符,它会自动为您提供正确类型的成员。

基本示例

#include <iostream>

class test
{
public:
    static const float f[2];
};

decltype(test::f) test::f = {1, 2};

int main(){
    // Outputs: 1, 2
    std::cout << test::f[0] << ", " << test::f[1];
}

现代例子

更现代的解决方案将使用std::arrayinitializer listauto 占位符类型说明符和constexpr 说明符。在这种情况下,您根本不需要提供数组大小。

#include <iostream>
#include <array>

class test
{
public:
    static constexpr auto f = std::array {1.f, 2.f};
};

int main(){
    // Outputs: 1, 2
    std::cout << test::f[0] << ", " << test::f[1];
}

【讨论】:

    【解决方案2】:

    正如@NathanOliver 所说,您可以将大小添加到类之外的初始化中:

    class test                                                                   
    {                                                                            
    public:                                                                      
        static const float f[2];                                                 
    };                                                                           
    ...                                                                          
    const float test::f[2] = {1, 2};
    

    或者,您也可以使用constexpr 并在类本身中声明数组:

    class test                                                                  
    {                                                                           
    public:                                                                     
        static constexpr float f[2] = {1, 2};                                   
    };
    

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2011-06-28
      相关资源
      最近更新 更多