开发者

C++ Simple Variant Boost

I'm attempting to create a list of objects using the variant boost.

#include <string>
#include <list>
#include <iostream>
#include <boost/variant.hp开发者_运维技巧p>

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;
}

Unfortunately, the following error is produced:

/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

I realise that everything would be fine if i used the form:

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);

But i would like to avoid that form if at all possible, since i would like to keep my objects unnamed. This is an important requirement for my system - is there any way i can avoid using named objects?


Just need to change a few things and it works:

#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;
}

Specifically, you needed to define the CRectangle and CSquare constructors (that's why you were getting a linker error) and to use CSquare() rather than new CSquare() etc. Also, "Hello World!" has type const char *, so you need to write string("Hello World!") when passing it to push_back or it will get implicitly converted to bool here (not what you want).


Instead of List.push_back(new CSquare()); just write

List.push_back(CSquare());

And also write defination of your constructor


You forget to implement the constructors CRectangle::CRectangle() and CSquare::CSquare().

Either implement them somewhere outside the class such as:

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

... or implement them inside the class:

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

... or remove the constructor declarations altogether:

class CRectangle {
public:
}; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜