【问题标题】:Using from base in derived class C++在派生类 C++ 中使用 from base
【发布时间】:2021-03-02 21:35:48
【问题描述】:

从“The C++ Programming Language 4th edition”(第1215页)的这段代码sn-p,我不明白“using”的用法;这些方法没有被派生类覆盖;为什么不直接从线程的正常继承中使用这两种方法呢?

struct guarded_thread : thread {
    using thread::thread;
    using thread::operator=;
    ~guarded_thread() { if (joinable()) join(); }
}

【问题讨论】:

    标签: c++ class inheritance using base


    【解决方案1】:

    你不能在没有明确告诉你想要这样做的情况下将构造函数与你派生的类的参数一起使用!

    如果您不想使用构造函数的using,则必须为您自己的类编写构造函数的所有变体,并将所有参数手动转发给您派生的类的构造函数。很多工作都是白做的!因此,只需告诉编译器,我们要使用派生类的构造函数。可以使用了!

    由于operator= 也是一个特殊函数,只要我们不提供一些,编译器会自行生成,我们还必须告诉编译器我们只想使用派生类中的函数。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2017-06-01
      相关资源
      最近更新 更多