简体   繁体   English

为什么我无法创建我的数组(C ++)?

[英]Why I can't create my array (C++)?

I have the following code: 我有以下代码:

#pragma once

class Matrix{
public:
    Matrix();
    ~Matrix();

protected:
    float mat[3] = {0.0, 0.0, 0.0};
};

but I'm getting an error on the float mat[3] = {0.0, 0.0, 0.0}; 但是我在float mat[3] = {0.0, 0.0, 0.0};得到一个错误float mat[3] = {0.0, 0.0, 0.0}; . It says Error C2059: syntax error : '{' and error C2334: unexpected token(s) preceding '{'; 它说错误C2059:语法错误:'{'和错误C2334:'{'之前的意外标记; skipping apparent function body. 跳过明显的功能体。

I am create the array correctly aint I? 我正确地创建了数组吗? What is the problem then? 那有什么问题呢?

C++03 does not support inline initialization of member fields. C ++ 03不支持成员字段的内联初始化。 You need to move this initialization into the constructor, for example ( link to a demo ): 您需要将此初始化移动到构造函数中,例如( 链接到演示 ):

class Matrix{
public:
    Matrix() : mat({0.0, 0.0, 0.0}) {};
    ~Matrix();

protected:
    float mat[3];
};

The above defines the constructor inline; 上面定义了内联构造函数; if you define the constructor separately, move the initialization list (ie the code between the colon : and the opening brace { ) together with the constructor definition. 如果单独定义构造函数,请将初始化列表(即冒号:和左大括号{之间的代码)与构造函数定义一起移动。

C++ did not support non-static data member initializers until after C++11 standard was ratified. 在批准C ++ 11标准之前,C ++不支持非静态数据成员初始值设定项 In order to use this feature, you must have a compiler that supports C++11. 要使用此功能,您必须具有支持C ++ 11的编译器。 Also, it is often disabled by default, so you will probably need to enable it manually. 此外,它通常默认禁用,因此您可能需要手动启用它。 For GCC, specify std=c++11 . 对于GCC,请指定std=c++11 For Clang, do -std=c++11 -stdlib=libc++ . 对于Clang,请执行-std=c++11 -stdlib=libc++ If you use something else, check the documentation. 如果您使用其他内容,请查看文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能打印出我的字符串数组c ++? - Why can't I print out my string array c++? 为什么我可以在 C++ 中动态创建静态数组? - Why can I create a static array dynamically in c++? 为什么我不能在C ++中输入我的std :: vector - Why I can't input into my std::vector in C++ 为什么我不能在C ++中填充此2D数组? - Why can't I fill this 2D array in C++? U +究竟是什么代表什么,为什么我不能在我的C ++应用程序中创建一个Unicode中间字符串表? - What exactly does U+ stand for and why can't I create a table of Unicode intermediate strings in my C++ application? 不知道为什么不能在C++中初始化一个数组 - I don't know why I can't initialize an array of an array in C++ 我可以在Python中创建C ++对象,但无法访问方法 - I can create my C++ object in Python, but can't access methods C ++为什么用另一个覆盖文本数组后,它的文本数组不会改变? - C++ Why won't my array of text change after I override it with another? 在C ++中删除后,为什么我不能重用动态分配的数组的名称? - Why can't I reuse the name of a dynamically-allocated array after I delete it in C++? 为什么我不能返回阵列? - Why my I can't return an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM