如何在C ++中使用基类的构造函数和赋值运算符? [英] How to use base class's constructors and assignment operator in C++?

查看:309
本文介绍了如何在C ++中使用基类的构造函数和赋值运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个B类,一组构造函数和一个赋值操作符。

I have class B with a set of constructors and an assignment operator.

class B
{
 public:
  B();
  B(const string & s);
  B(const B & b){(*this) = b;};
  B & operator= (const B & b);
 private:
  virtual void foo();
  // and other private member variables and functions
}

创建继承类D,它将仅覆盖函数foo(),并且不需要其他更改。

I want to create an inheriting class D that will just override the function foo(), and no other change is required.

但我想让D拥有相同的构造函数集,包括复制构造函数和作为B的赋值运算符:

But I want D to have the same set of constructors, including copy constructor and assignment operator as B:

  D(const D & d){(*this) = d;};
  D & operator= (const D & d);

我必须在D中重写所有这些,还是有一种方法来使用B的构造函数操作员?我特别想避免重写赋值操作符,因为它必须访问所有的B的私有成员变量。

Do I have to rewrite all of them in D, or is there a way to use B's constructors and operator? I would especially want to avoid rewriting the assignment operator because it has to access all of B's private member variables.

推荐答案

调用构造函数和赋值运算符:

You can explicitly call constructors and assignment operators:

class Base {
//...
public:
    Base(const Base&) { /*...*/ }
    Base& operator=(const Base&) { /*...*/ }
};

class Derived : public Base
{
    int additional_;
public:
    Derived(const Derived& d)
        : Base(d) // dispatch to base copy constructor
        , additional_(d.additional_)
    {
    }

    Derived& operator=(const Derived& d)
    {
        Base::operator=(d);
        additional_ = d.additional_;
        return *this;
    }
};

有趣的是,即使你没有明确定义这些函数编译器生成的函数)。

The interesting thing is that this works even if you didn't explicitly define these functions (it then uses the compiler generated functions).

class ImplicitBase { 
    int value_; 
    // No operator=() defined
};

class Derived : public ImplicitBase {
    const char* name_;
public:
    Derived& operator=(const Derived& d)
    {
         ImplicitBase::operator=(d); // Call compiler generated operator=
         name_ = strdup(d.name_);
         return *this;
    }
};  

这篇关于如何在C ++中使用基类的构造函数和赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆