0
#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*”。我在这里想念什么?

4

2 回答 2

1

你确实提供operator =

shared_ptr = shared_ptr 

案例(非常奇怪的运算符顺便说一句)。但是您正在尝试使用

int* = shared_ptr

您需要在 shared_ptr 中使用 getter 或 cast-operator 才能实现

实际上你可以像这样使用它

shared_ptr s1, s2;
...
int* k = (s1 = s2);

演示

但这绝对是丑陋的

于 2013-07-04T21:23:11.007 回答
1

你的Operator =回报int*,但你没有得到的构造函数int*,添加:

shared_ptr(int *other)
{
    pointer = new int(*other);
}
于 2013-07-04T21:33:39.263 回答