c++统一声明在类中不起作用



我试图在一个类中有一个成员数组,其长度由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测试版,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,因为这是您拥有的targetname。点击这里了解更多如何在CMake中激活c++ 11。

最新更新