如何在 c++ 中创建派生类
How to create derived class in c++
我对如何处理C++中的继承感到困惑
我想在构造函数上传递参数。但是当我创建一个没有参数的类时,我才运行它。
这个小程序:
#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int width, height;
public:
Shape(int w, int h) {
width = w;
height = h;
}
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
// New class Rectangle based on Shape class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
编译时出现错误:
$ g++ inheritance.cpp -o inheritance -g -std=c++11
inheritance.cpp:44:13: error: no matching constructor for initialization of 'Rectangle'
Rectangle r(3, 4)
^ ~~~~
inheritance.cpp:33:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class Rectangle: public Shape {
^
inheritance.cpp:33:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
inheritance.cpp:33:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided
构造
函数不是从Shape
继承的。您需要为 Rectangle
提供一个构造函数,该构造函数可以采用以下参数签名:
Rectangle(int w, int h) : Shape(w,h) { }
相关文章:
- 如何使用"derived input class"创建派生类?
- 创建派生自可变参数模板包的类型元组
- 如何创建派生对象的向量?
- 与简单地创建派生类指针相比,将基类绑定到派生类有什么优点?
- 在基类中创建派生类的对象
- 根据参数创建派生类的新实例
- 受保护的析构函数禁用在堆栈上创建派生类的对象?
- std ::移动不要创建派生类
- 如何从现有基类对象创建派生类对象
- 如何创建派生指针类变量
- 尝试在基类之外创建派生类的实例时出错
- 从基创建派生类
- 在 C++ 的父类中创建派生的 CARS
- C 双重调度,出厂模式或一种从接收到的序列数据创建派生对象的方法
- C++ 抽象类和创建派生类
- 在创建派生类实例时提供基类构造函数参数
- 使用基构造函数创建派生对象
- 创建派生类构造函数时出错
- 如何在C++的基类中创建派生类的对象数组
- 在 C++ 中创建派生类