C++继承的运算符未在派生类中调用
C++ inherited operator not being called in the derived class
我在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类。
运算符=被继承,但默认情况下由编译器生成。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- QWidget::p aintEngine:不应再在 QTreeWidget 派生类中调用
- 调用从模板派生的类的静态方法,而不指定模板
- 调用派生类成员函数
- 从基类实例调用派生类方法而不进行强制转换
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从 c++ 中派生类的析构函数调用虚函数
- 从基类 (C++) 调用派生类中的非虚函数
- 调用不在基类中的派生类函数而不进行动态强制转换,以最大程度地提高性能
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 如何使派生类函数在调用时始终调用相同的基类函数?
- C++初始化之前派生类调用基类的方法
- 为什么派生类的实例从基类调用方法?
- 从 Base 引用对象调用派生类的成员
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 基函数中的公共函数,当使用派生对象通过另一个基函数调用时,派生调用基函数