首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符重载赋值运算符

运算符重载赋值运算符
EN

Stack Overflow用户
提问于 2013-07-05 05:20:00
回答 2查看 163关注 0票数 0
代码语言:javascript
复制
#include<iostream>

using namespace std;


class shared_ptr
{
    public:
    int *pointer;
    public:
    shared_ptr()
    {
        pointer = new int;
    }
    ~shared_ptr()
    {
        delete pointer;
    }
    int operator* ();
    int* operator= (shared_ptr&);
};

int shared_ptr:: operator* ()
{
    return *(this->pointer);
}

int* shared_ptr:: operator= (shared_ptr& temp)
{
    return (temp.pointer);
}

int main()
{
    shared_ptr s1;
    *(s1.pointer) = 10;
    cout << *s1 << endl;
    int *k;
    k = s1;         //error
    cout << *k << endl;
}

我正在尝试创建类似于智能指针的东西。

当我试图重载操作符=时,我得到了以下错误。

prog.cpp:39:9:错误:无法在k= s1赋值行的赋值中将‘shared_ptr’转换为‘int*’。这里我漏掉了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-05 05:23:11

您确实为以下对象提供了operator =

代码语言:javascript
复制
shared_ptr = shared_ptr 

case(非常奇怪的运算符btw)。但你正试图利用

代码语言:javascript
复制
int* = shared_ptr

您需要在shared_ptr中使用getter或cast-operator来实现这一点

实际上,您可以像这样使用它

代码语言:javascript
复制
shared_ptr s1, s2;
...
int* k = (s1 = s2);

Demo

但它绝对是丑陋的

票数 1
EN

Stack Overflow用户

发布于 2013-07-05 05:33:39

您的Operator =返回int*,但您没有获取int*的构造函数,请添加:

代码语言:javascript
复制
shared_ptr(int *other)
{
    pointer = new int(*other);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17478212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档