C++ 统一声明在 class 中不起作用

C++ uniform declaration is not working in class

我正在尝试在 class 中创建一个成员数组,其长度由 const static int 变量指定以备将来需要。

我的编译器抛出一个错误,我不确定这是关于统一初始化或数组初始化的错误,还是两者都有。

这是头文件:

#ifndef SOUECE_H
#define SOURCE_H

class Test
{
public:
    Test();
    static const int array_length{2};
    double array[array_length];
};

#endif

这是源文件。

#include "source.h"

Test::Test()
    :array_length{0} //Typo of array{0}
{
}

这些是问题消息。
[在此处输入图片描述][1] [1]: https://i.stack.imgur.com/IQ2Mk.png

这是 CMake 文件。

cmake_minimum_required(VERSION 3.0.0)
project(temp VERSION 0.1.0)

include(CTest)
enable_testing()

add_executable(temp main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

最后,这些是编译器在我尝试构建项目时抱怨的内容。

[main] Building folder: temp 
[build] Starting build
[proc] Executing command: /usr/local/bin/cmake --build /Users/USERNAME/Desktop/temp/build --config Debug --target all -j 14 --
[build] [1/2  50% :: 0.066] Building CXX object CMakeFiles/temp.dir/main.cpp.o
[build] FAILED: CMakeFiles/temp.dir/main.cpp.o 
[build] /usr/bin/clang++   -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.3.sdk -MD -MT CMakeFiles/temp.dir/main.cpp.o -MF CMakeFiles/temp.dir/main.cpp.o.d -o CMakeFiles/temp.dir/main.cpp.o -c ../main.cpp
[build] In file included from ../main.cpp:1:
[build] ../source.h:8:22: error: function definition does not declare parameters
[build]     static const int array_length{2};
[build]                      ^
[build] ../source.h:9:18: error: use of undeclared identifier 'array_length'
[build]     double array[array_length];
[build]                  ^
[build] 2 errors generated.
[build] ninja: build stopped: subcommand failed.
[build] Build finished with exit code 1

我使用的是 macOS 12.0 beta,VS Code 1.60.2,clang 13.0.0,CMake 3.20.2。

如果您发现任何错误或有任何建议,请告诉我。

这行不通:

Test::Test()
    :array_length{0}

您不能在构造函数中设置 const static 数据成员。 static 值在所有对象实例中具有相同的值。但因为它也是 const 不允许实例更改值。

因为 array_lengthstatic const 你必须像这样初始化它:

source.h

#ifndef SOUECE_H
#define SOURCE_H

class Test
{
public:
    Test();
    static const int array_length = 2;
    //static const int array_length{2}; this will also work just note that we cannot use constructor initializer list to initialize static data members
    double array[array_length];
};

#endif

source.cpp

#include "source.h"

Test::Test()//we cannot use constructor initializer list to initialize array_length
    
{
}

请注意 static const int array_length{2}; 也可以工作,但问题是在构造函数中我们不能使用构造函数初始化列表来初始化静态数据成员。

编辑: 如果您决定使用 static const int array_length{2};,那么请确保您在 CMakeLists.txt 中启用了 C++11(或更高版本)。为此,您可以添加

set (CMAKE_CXX_STANDARD 11)

给你的 CMakeLists.txt.

或者,您可以添加

target_compile_features(targetname PUBLIC cxx_std_11)

在你的 CMakeLists.txt 中。在您的情况下,将 targetname 替换为 temp 因为那是您拥有的目标名称。查看更多 how to active C++11 in CMake .