【问题标题】:C++ Simple Variant BoostC++ 简单变体增强
【发布时间】:2011-01-16 20:32:48
【问题描述】:

我正在尝试使用变体 boost 创建一个对象列表。

#include <string>
#include <list>
#include <iostream>
#include <boost/variant.hpp>

using namespace std;
using namespace boost;   

class CSquare;

class CRectangle {
public:
  CRectangle();
};

class CSquare {
public:
  CSquare();
};

int main()
{   typedef variant<CRectangle,CSquare, bool, int, string> object;

    list<object> List;

    List.push_back("Hello World!");
    List.push_back(7);
    List.push_back(true);
    List.push_back(new CSquare());
    List.push_back(new CRectangle ());

    cout << "List Size is: " << List.size() << endl;

    return 0;
}

不幸的是,产生了以下错误:

/tmp/ccxKh9lz.o: In function `main':
testing.C:(.text+0x170): undefined reference to `CSquare::CSquare()'
testing.C:(.text+0x203): undefined reference to `CRectangle::CRectangle()'
collect2: ld returned 1 exit status

我意识到如果我使用表格一切都会好起来的:

CSquare x;
CRectangle y;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
List.push_back(x);
List.push_back(y);

但我想尽可能避免这种形式,因为我想保持我的对象不命名。这是我的系统的重要要求 - 有什么方法可以避免使用命名对象?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    只需要改变一些东西就可以了:

    #include <iostream>
    #include <list>
    #include <string>
    #include <boost/variant.hpp>
    using namespace std;
    using namespace boost;   
    
    class CRectangle
    {
    public:
     CRectangle() {}
    };
    
    class CSquare
    {
    public:
     CSquare() {}
    };
    
    int main()
    {
     typedef variant<CRectangle, CSquare, bool, int, string> object;
     list<object> List;
     List.push_back(string("Hello World!"));
     List.push_back(7);
     List.push_back(true);
     List.push_back(CSquare());
     List.push_back(CRectangle());
    
     cout << "List Size is: " << List.size() << endl;
    
     return 0;
    }
    

    具体来说,您需要定义 CRectangle 和 CSquare 构造函数(这就是您收到链接器错误的原因)并使用 CSquare() 而不是 new CSquare() 等。此外,"Hello World!" 的类型为 const char *,所以您将string("Hello World!") 传递给push_back 时需要写,否则它会在此处隐式转换为bool(不是您想要的)。

    【讨论】:

      【解决方案2】:

      而不是 List.push_back(new CSquare());随便写

      List.push_back(CSquare());
      

      还要写下你的构造函数的定义

      【讨论】:

        【解决方案3】:

        您忘记实现构造函数CRectangle::CRectangle()CSquare::CSquare()

        要么在类之外的某个地方实现它们,例如:

        CRectangle::CRectangle()
        { 
            // :::
        }; 
        

        ...或在类中实现它们:

        class CRectangle {
        public:
          CRectangle()
          { 
            // :::
          }
        }; 
        

        ...或完全删除构造函数声明:

        class CRectangle {
        public:
        }; 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          相关资源
          最近更新 更多