运算符重载赋值运算符

时间:2013-07-04 21:20:00

标签: c++

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

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

尝试重载operator =时出现以下错误。

prog.cpp:39:9:错误:在为k = s1分配行的赋值中,无法将'shared_ptr'转换为'int *'。 我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

您确实为

提供了operator =
shared_ptr = shared_ptr 

案例(非常奇怪的运营商btw)。但是你正在尝试使用

int* = shared_ptr

您需要在shared_ptr中使用getter或cast-operator才能使其成为可能

实际上你可以像

一样使用它
shared_ptr s1, s2;
...
int* k = (s1 = s2);

Demo

但这绝对是丑陋的

答案 1 :(得分:1)

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

shared_ptr(int *other)
{
    pointer = new int(*other);
}