【问题标题】:List of pairs of strings initialization in constructor构造函数中的字符串对初始化列表
【发布时间】:2019-07-26 15:44:09
【问题描述】:

我有两个类,调度程序和 cshw 类。调度器的构造函数需要std::list < std::pair<std::string, std::string> > names。 CSHW 类继承自调度程序,并且在 cshw 类的构造函数中我执行cshw::cshw():scheduler ({std::make_pair("mfp", "MFP") }){ 我得到一个未找到符号的错误。 我基本上需要将一对字符串列表传递给调度程序构造函数,这在 c++11 中有效,但我只在 c++98 中遇到这个问题


#ifndef SCHEDULER_H_
#define SCHEDULER_H_

#include <list>
#include <utility>
#include <string>

class scheduler {
public:
               std::list < std::pair<std::string, std::string>  > names;
               scheduler(std::list < std::pair<std::string, std::string> > names);
               virtual ~scheduler();
};

class cshw : public scheduler{
public:
               std::list < std::pair<std::string, std::string>  > m_szPanelNames;
               cshw();
               virtual ~cshw();
};

scheduler::scheduler(std::list < std::pair<std::string, std::string> > pnames) {
               names = pnames;
}

scheduler::~scheduler() {
}

cshw::cshw():
                              scheduler ({std::make_pair("mfp", "MFP") }){
}

cshw::~cshw() {
               // TODO Auto-generated destructor stub
}
#endif /* SCHEDULER_H_ */

我得到一个构造函数不匹配调度程序的错误。我认为这是由于我试图将列表对初始化为参数造成的。 在 c++98 中传递对列表作为参数的方法是什么?

【问题讨论】:

    标签: gcc std-pair c++98 stdlist


    【解决方案1】:

    您可以在cshw 中添加生成列表的辅助方法:

    class cshw : public scheduler{
    public:
                   std::list < std::pair<std::string, std::string>  > m_szPanelNames;
                   cshw();
                   virtual ~cshw();
    
                  // added
                  std::list< std::pair<std::string,std::string> > genList()
                  {
                      std::list< std::pair<std::string,std::string> > l;
                      l.push_back(std::make_pair("mfp","MFP"));
                      return l;
                  }
    };
    

    然后将其结果作为参数传递给初始化列表中的scheduler

    cshw::cshw():
       scheduler ( genList() ) 
    {;}
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2013-10-03
      • 1970-01-01
      • 2014-07-14
      • 2017-03-07
      • 1970-01-01
      相关资源
      最近更新 更多