繁体   English   中英

使用非默认构造函数初始化成员变量会出错

[英]Member variable initialization with non-default constructor gives error

robots.h:11:20: 错误:数字常量队列 SQ(10) 之前的预期标识符;

struct Robot
{
  string m_name; //robot name
  Queue<string> SQ(10); //queue of services
  int m_timer; //time til robot is done
  string m_lastService; //most recent service
};

我不明白为什么我会在这方面出错。 当我拿走 (10) 时,它使用了默认构造函数并且工作正常。 这是 Queue 类。

template <typename T>
class Queue : public AbstractQueue<T>
{
  private:
    T* m_array;
    int m_front;
    int m_back;
    int m_capacity;
    int m_size;
  public:
    Queue();
    Queue(int max);
    void setMax(int max);
    bool isEmpty() const;
    const T& front() const throw (Oops);
    const T& back() const throw (Oops);
    void enqueue(const T& x);
    void dequeue();
    void clear();
    ~Queue();
};

我使用了 Queue 类的另一个声明,它在 main 中工作,但由于某种原因它在结构中不起作用,这是我在 main 中声明的

Queue<Robot> R(10);

您不能像这样指定用于成员变量初始化的非默认构造函数。

您可以提供一个带有成员初始值设定项列表的构造函数来指定要使用的Queue的构造函数。

struct Robot
{
  string m_name; //robot name
  Queue<string> SQ(); //queue of services
  int m_timer; //time til robot is done
  string m_lastService; //most recent service
  Robot() : SQ(10) {}
};

或者使用默认成员初始值设定项(c++11 起):

Queue<string> SQ{10};

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM