【发布时间】:2018-05-24 19:29:44
【问题描述】:
如果我将我的类分成头文件/实现文件,是否可以在不需要在子类中重新声明继承属性的情况下进行继承?
让我用一个例子来澄清一下。为什么允许这样做(取自here):
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
但这不是(尝试编译here):
#include <string>
#include <iostream>
// HEADER FILE
class Person {
public:
virtual void speak() = 0;
protected:
std::string name;
std::string surname;
};
class Programmer : public Person {
public:
Programmer(std::string, std::string);
};
// CPP FILE
Programmer::Programmer(std::string name, std::string surname) :
name(name),
surname(surname)
{}
void Programmer::speak(){
std::cout << "My name is " + name + " " + surname + " and I like to code!";
}
【问题讨论】:
-
您没有声明
Programmer来实现名为speak的函数 - 在某些情况下您不会为类中的virtual函数创建覆盖(这通常是适用于任何 OOP 语言) -
@UnholySheep 但是属性
name和surname呢?我收到关于Programmer的错误,也没有这些错误。 -
那是因为它们受到保护。导致错误的完全不同的原因。
标签: c++ oop inheritance