C++ 运算符重载赋值运算符 #包括 使用名称空间std; 类共享\u ptr { 公众: int*指针; 公众: 共享_ptr() { 指针=新整数; } ~shared_ptr() { 删除指针; } int运算符*(); int*运算符=(共享的); }; int shared_ptr::operator*() { 返回*(此->指针); } int*shared_ptr::operator=(shared_ptr&temp) { 返回(温度指针); } int main() { 共享ptr s1; *(s1.指针)=10; cout

C++ 运算符重载赋值运算符 #包括 使用名称空间std; 类共享\u ptr { 公众: int*指针; 公众: 共享_ptr() { 指针=新整数; } ~shared_ptr() { 删除指针; } int运算符*(); int*运算符=(共享的); }; int shared_ptr::operator*() { 返回*(此->指针); } int*shared_ptr::operator=(shared_ptr&temp) { 返回(温度指针); } int main() { 共享ptr s1; *(s1.指针)=10; cout,c++,C++,您确实为提供了operator= #include<iostream> using namespace std; class shared_ptr { public: int *pointer; public: shared_ptr() { pointer = new int; } ~shared_ptr() { delete pointer; } int opera

您确实为提供了
operator=

#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;
}
案例(非常奇怪的操作员顺便说一句)。但您正在尝试使用

shared_ptr = shared_ptr 
您需要在shared_ptr中使用getter或cast操作符来实现这一点

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

int* = shared_ptr


但它绝对难看

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

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

“我在这里遗漏了什么?”一个cast?我可以在不需要cast的地方实现吗?我的意思是使用类似指针的方式分配内存,然后复制将是一个好主意,我认为,否则您可能会成为segfault的牺牲品
shared_ptr(int *other)
{
    pointer = new int(*other);
}