C ++重载运算符=指针无法正常工作/编译

编程入门 行业动态 更新时间:2024-10-19 04:21:24
本文介绍了C ++重载运算符=指针无法正常工作/编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用=的运算符重载来实现模板类 到目前为止,它适用于非指针元素.对于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 ++重载运算符=指针无法正常工作/编译

本文发布于:2023-06-03 12:19:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473795.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   无法正常   运算符   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!