我正在尝试使用=的运算符重载来实现模板类 到目前为止,它适用于非指针元素.对于Pointer Elements,它不能完全按我的预期工作,所以我的问题是为什么要播种,以及如何强制c ++按我的意愿进行操作.
I am trying to implement a template Class with an Operator Overload for = so far it works for non pointer elements. For Pointer Elements it doesn't work exactly as I expect it to, so my question is why this is sow and how do I force c++ do it as I want.
我的模板类:
template <class T> class IBag { public: T _val; void Set(T val) { _val = val; } T Get() { return _val; } IBag& operator=(T val) { this->Set(val); return *this; } operator T() { return this->Get(); } };使用IBag类如何工作:
How it works using the IBag Class:
class IBagExample { void showExample() { IBag<QString*> pbag; pbag = new QString("Blub"); // This works ! } };它如何不编译:
class IBagExample { void showExample() { IBag<QString*> pbag = new QString("Blub"); // This doesn't compile ! } };我得到的编译器错误是:
The compiler Error I get is :
error: no viable conversion from 'QString *' to 'IBag<QString *>' IBag<QString*> pbag2 = new QString("Blub"); ^ ~~~~~~~~~~~~~~~~~~~对我来说似乎是相同的,也许我需要告诉编译器一些信息,以了解现在将哪种类型的指针推入pbag中.但是我不知道该怎么做.
For me it seems the same, maybe I need to tell the compiler something to understand what type of pointer is now going to be pushed into the pbag. But I have no Idea how to do that.
使用像
IBag<QString*> pbag; pbag = new QString("Blub"); // This does compile !似乎太荒谬了.
(注意:IBag示例只是我要实现的代码的简化.)
(Note:The IBag example is just a simplification of the Code I am trying to implement.)
非常感谢
推荐答案IBag<QString*> pbag = new QString("Blub");
这实际上没有调用赋值运算符,而是调用了构造函数.您需要定义如下内容:
This doesn't actually call the assignment operator, it calls a constructor. You need to define that something like:
template <class T> class IBag { public: IBag( const IBag& rhs ) { // .... } };或:
IBag( const T& rhs ) { // .... }更多推荐
C ++重载运算符=指针无法正常工作/编译
发布评论