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

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

问题描述

我有一个 B 类,其中包含一组构造函数和一个赋值运算符.

I have a 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天全站免登陆