C ++中的赋值运算符重载(使用指针对象)

时间:2019-11-19 16:32:23

标签: c++ pointers overloading operator-keyword

我有一个简单的类,它具有整数指针,赋值运算符重载和...。然后,我声明两个指针对象(t1和t2),并将t2分配给t1。 问题是此分配是默认的副本分配运算符,我不希望这样。

#include <iostream>

using namespace std;

class Test{
    int *x;
public:
    Test(int val =0 ):x{new int(val)}{}
    void setX(int val){*x = val;}
    void print(){cout<< "OUTPUT:"<< *x<<endl;}
    ~Test(){delete x;}

    Test* operator = (const Test* rhs){
        if(this != rhs)
            *x = *(rhs->x);
        return this;
    }
};
 int main(){
    Test* t1 = new  Test(5);
    Test* t2 = new Test(10);
    t1 = t2;

    t1->setX(1555);
    t1->print();
    t2->print();

 }

下面的代码运行良好,但是我需要将对象作为指针(实际上,我在一个对象是模板指针的项目中工作,并且遇到了相同的问题(调用了默认的复制赋值运算符。)):

class Test{
    int *x;
public:
    Test(int val =0 ):x{new int(val)}{}
    void setX(int val){*x = val;}
    void print(){cout<< "OUTPUT:"<< *x<<endl;}
    ~Test(){delete x;}

    Test& operator = (const Test& rhs){
        if(this != &rhs)
            *x = *rhs.x;
        return *this;
    }
};
 int main(){
    Test t1(5);
    Test t2(10);
    t1 = t2;

    t1.setX(1555);
    t1.print();
    t2.print();

 }

0 个答案:

没有答案
相关问题