【问题标题】:copy constructor, operator= in a child class复制构造函数,子类中的 operator=
【发布时间】:2021-05-13 15:17:24
【问题描述】:

我想创建一个operator= 和复制构造函数,以便在继承的类中调用。

对于普通对象,它可以正常工作,但是当我尝试使用指针调用 operator= 时,它只是在复制对象地址。

所以我的问题是,如何使用指针调用这些方法?

#include <iostream>

// base class
class a {     
public:
    //constructors
    a(): x(0), y(1), z(0){ std::cout << "no parameter constructor A\n"; }
    a(int a, int b, int c) :x(a), y(b), z(c){ std::cout << "parameter constructor A\n"; }
    a(const a& ob):x(ob.x), y(ob.y), z(ob.z)
    {
        std::cout << "copy constructor A\n";
    }
    //operator
    a& operator=(const a& obj) 
    {
        if (this != &obj)
        {
            x = obj.x;
            y = obj.y;
            z = obj.z;
        }
        std::cout << "operator = A\n";
        return *this;   
    }
protected:
    int x, y, z;
};

//child class
class b : public a
{
public:
    //constructors
    b() : p(0){ std::cout << "no parameter constructor B\n"; }
    b(int X, int Y, int Z, int B) : a(X, Y, Z), p(B) { std::cout << "parameter constructor B\n"; }
    b(const b& obj) :p(obj.p), a(obj)
    {
        std::cout << "copy constructor B\n";
    }
    //operator =
    b& operator=(const b &obj)
    {
        if (this != &obj)
        {
            p = obj.p;
            &a::operator=(obj);
        }
        std::cout << "operator = B\n";
            return *this;
    }
private:
    int p;
};

int main()
{
    b obj0(4, 8, 16, 32);
    b obj1(obj0);   // copy constructor
    b obj2;
    obj2 = obj1;    // operator =
    std::cout << std::endl << std::endl;
    std::cout << "for pointers:\n\n";
    a* obj3 = new b(4, 8, 16, 32);
    a* obj4(obj3);
    obj4 = obj3;
    return 0;
}

【问题讨论】:

标签: c++ pointers inheritance


【解决方案1】:

使用指针(或引用)的目的之一是避免需要创建对象的副本。将指针传递给对象允许接收者引用和操作原始对象。

如果你希望指针接收一个新对象,那么你可以使用new。

在您的示例中处理多态性时,您可能需要一个虚拟方法来创建正确的克隆(有时称为深拷贝)。

class a {
    //...
    virtual a * clone () const = 0;
};

class b : public a {
    //...
    b * clone () const {
        return new b(*this);
    }
};

//...
    a *obj4 = obj3->clone();
//...

我们利用b * 是a * 的协变返回类型,因此b::clone() 可以返回b *,但a::clone() 可以使用b::clone() 作为覆盖并仍然返回@987654329 @。

【讨论】:

  • 使用“协变返回类型”的好地方...b:::clone() 应该返回b* 而不是a*。此外,clone() 应该是 const。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2013-04-04
  • 2017-08-25
相关资源
最近更新 更多