C++继承的运算符未在派生类中调用

C++ inherited operator not being called in the derived class

本文关键字:派生 调用 继承 运算符 C++      更新时间:2023-10-16

我在C++中有以下代码

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class A{
  public:
    int x;
    int y;
    int first(){
      return x;
    }
    int second(){
      return y;
    }
};
class C{
  public:
    float a,b;
    C(){
      a = 0.0f;
      b = 0.0f;
    }
    template<class T>
      C(T t){
        cout<<"Copy Constructorn";
        a = t.first();
        b = t.second();
      }
      template<class T>
    C & operator=(T const &c){
        cout <<"Assignment operatorn";
        this->a = c.first();
        this->b = c.first();
    }
};
class D: public C{
  public:
    template <typename T> D (T t) : C(t) {}
    float area(){
      return a*b; 
    }
};
int main(){
  A a;
  a.x = 6;
  a.y = 8;
  C c(a);
  D d(a);
  D e = a;   // Here copy constructor is being called!!
  cout<<e.a<<" "<<e.b<<" "<<e.area()<<endl;
}

这是上述程序的输出

Copy Constructor
Copy Constructor
Copy Constructor
6 8 48

为什么在派生类中不调用赋值运算符?

编辑1:我更改了问题以使问题更清晰。

构造函数不是作为常规公共函数继承的。如果缺少默认构造函数,则由编译器定义,但您应该定义一个构造函数,该构造函数采用A参数(或像C那样模板化)进行D。您还需要定义赋值运算符。

class D: public C{
  public:
    D(A aparam)
    : a(aparam.first(), b(aparam.second()){
    }
    D& operator=(const D& rhs){
      a = rhs.first();
      b = rhs.second();
    }
    float area(){
      return a*b; 
    }
};
您可以使用以下

方法显式地取回所述运算符=:

using C::operator=

在D类。

运算符=被继承,但默认情况下由编译器生成。