无法初始化静态QList?

dfe*_*r88 5 c++ qt static

我收到以下错误:

Cube.cpp:10: error: expected initializer before ‘<<’ token

这是头文件的重要部分:

#ifndef CUBE_H
#define CUBE_H

#include <cstdlib>
#include <QtCore/QtCore>
#include <iostream>

#define YELLOW 0
#define RED 1
#define GREEN 2
#define ORANGE 3
#define BLUE 4
#define WHITE 5

using namespace std;

class Cube {
public:
  ...
  static QList<int> colorList;
  ...
};
#endif
Run Code Online (Sandbox Code Playgroud)

这是给出错误的行:

QList<int> Cube::colorList << YELLOW << RED << GREEN << ORANGE << BLUE << WHITE;
Run Code Online (Sandbox Code Playgroud)

Lou*_*nco 8

您无法使用初始化对象<<.在=这通常是没有operator=()-这是一个特殊的语法在本质上是一样调用构造函数.

这样的事可能有用

QList<int> Cube::colorList = EmptyList() << YELLOW << RED << GREEN << ORANGE << BLUE << WHITE;
Run Code Online (Sandbox Code Playgroud)

其中EmptyList()是

QList<int> EmptyList()
{
   QList<int> list;
   return list;
}
Run Code Online (Sandbox Code Playgroud)

并且是列表的复制结构,并禁止一些优化,创建列表的副本.

  • 谢谢.我使用了类似于你提供的东西.我使用了新的QList <int>()<< ...;而不是空列表.它似乎工作.您是否发现使用此方法存在任何潜在问题? (2认同)