【问题标题】:How to initialize array out of the class and set a value to the first element?如何从类中初始化数组并将值设置为第一个元素?
【发布时间】:2019-10-17 07:43:52
【问题描述】:

在 Arduino 中使用。问题就在那里:Player::coords[0] = {0, 0};

头文件:

#ifndef game_h
#define game_h
#include <Arduino.h>

class Player {
  public:
    int getScore();
    static int coords[3250][2];
    coordinates: x, y

  private:
    static int score;
};

#endif

Cpp 文件:

#include "game.h"

int Player::score = 1;

int Player::getScore() {
  return this->score;
}

int Player::coords[3250][2];
Player::coords[0] = {0, 0};

编译器写道:'class Player' 中的'coords' 没有命名类型

【问题讨论】:

  • 你不能在函数之外分配变量。

标签: c++ arrays class static initialization


【解决方案1】:

你不能在命名空间范围内这样做

int Player::coords[3250][2];
Player::coords[0] = {0, 0};

其实这些语句等价于这个

int Player::coords[3250][2] = { { 0, 0 } };

或

int Player::coords[3250][2] = {};

甚至只是

int Player::coords[3250][2];

因为数组具有静态存储持续时间,并且被编译器初始化为零。

【讨论】:

    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多