(删除原始文本,因为它与当前已回答的问题无关。请参阅修订。)
以下是我的示例test.hpp
(简化):
class House {
private:
int nWindows;
public:
House(int nWindows);
int getNumberOfWindows();
};
class PaintedHouse : public virtual House {
private:
int colorCode;
public:
PaintedHouse(int nWindows, int colorCode);
int getColorCode();
};
class OccupiedHouse : public virtual House {
private:
int nPeople;
public:
OccupiedHouse(int nWindows, int nPeople);
int getNumberOfPeople();
};
class PaintedOccupiedHouse : public PaintedHouse, OccupiedHouse {
public:
PaintedOccupiedHouse(int nWindows, int colorCode, int nPeople);
};
test.cpp
:
#include "test.hpp"
House::House(int nWindows) { this->nWindows = nWindows; }
int House::getNumberOfWindows() { return this->nWindows; }
PaintedHouse::PaintedHouse(int nWindows, int colorCode) : House(nWindows) {
this->colorCode = colorCode;
}
int PaintedHouse::getColorCode() { return this->colorCode; }
OccupiedHouse::OccupiedHouse(int nWindows, int nPeople) : House(nWindows) {
this->nPeople = nPeople;
}
int OccupiedHouse::getNumberOfPeople() { return this->nPeople; }
PaintedOccupiedHouse::PaintedOccupiedHouse(int nWindows, int colorCode, int nPeople)
: PaintedHouse(nWindows, colorCode), OccupiedHouse(nWindows, nPeople) {}
海湾合作委员会回归:
test.cpp: In constructor ‘PaintedOccupiedHouse::PaintedOccupiedHouse(int, int, int)’:
test.cpp:18:72: error: no matching function for call to ‘House::House()’
: PaintedHouse(nWindows, colorCode), OccupiedHouse(nWindows, nPeople) {}
^
test.cpp:18:72: note: candidates are:
test.cpp:4:1: note: House::House(int)
House::House(int nWindows) { this->nWindows = nWindows; }
^
test.cpp:4:1: note: candidate expects 1 argument, 0 provided
In file included from test.cpp:2:0:
test.hpp:2:7: note: constexpr House::House(const House&)
class House {
^
test.hpp:2:7: note: candidate expects 1 argument, 0 provided
test.hpp:2:7: note: constexpr House::House(House&&)
test.hpp:2:7: note: candidate expects 1 argument, 0 provided
你能告诉我我做错了什么吗?一般概念是否正确?
答案 0 :(得分:2)
替换
PaintedOccupiedHouse::PaintedOccupiedHouse(int nWindows, int colorCode, int nPeople)
: PaintedHouse(nWindows, colorCode), OccupiedHouse(nWindows, nPeople) {}
通过
PaintedOccupiedHouse::PaintedOccupiedHouse(int nWindows, int colorCode, int nPeople)
: House(nWindows), PaintedHouse(nWindows, colorCode), OccupiedHouse(nWindows, nPeople) {}
如果有虚拟继承,则只有virtual
基类的一个实例。它必须在构造的派生类最多的构造函数中初始化。
答案 1 :(得分:1)
我建议将Painting
和Occupied
内容分成不同的类。
因此你可以:
Painted House Occupied
| | |
+---------+--------+
|
Painted_Occupied_House
不希望设置可怕的钻石继承。看看你是否可以重构来缓解这个问题。
钻石界面带来了注入更多缺陷的可能性。