C++ Simple Variant Boost

Ram*_*sey 3 c++ boost

我正在尝试使用变量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;
}
Run Code Online (Sandbox Code Playgroud)

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

/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
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

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

Stu*_*etz 5

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

具体来说,你需要定义CRectangle和CSquare构造函数(这就是你得到链接器错误的原因)并使用CSquare()而不是new CSquare()等等.另外,"Hello World!"有类型const char *,所以你需要string("Hello World!")在传递它时写push_back或者它会被隐式转换为bool这里(不是你想要的).