1
Я запутался о том, как иметь дело с наследованием в 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
Просто добавьте 'Прямоугольник (Int W, внутр ч): Форма (ш, ч) {};' – DimChtz
@DimChtz Почему вы отвечаете на вопросы в комментарии? Это не то, для чего предназначена эта функция. –
@ πάνταῥεῖ Вы правы, извините – DimChtz