0
爲什麼我必須在SuperCopier的構造函數中調用PoweredDevice?直接創建複印機對象時,複印機的構造函數已經初始化。爲什麼要在子派生類中構建虛擬基礎?
是否有任何簡單的方法來封裝複印機? (只是使用它的構造函數,並不在乎它的基地。)
下面的代碼是從http://www.learncpp.com/cpp-tutorial/128-virtual-base-classes/幾乎沒有任何修改。
#include <iostream>
class PoweredDevice
{
public:
PoweredDevice(int power)
{
std::cout << "PoweredDevice: " << power << '\n';
}
};
class Scanner: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class
{
public:
Scanner(int scanner, int power)
: PoweredDevice(power) // this line is required to create Scanner objects, but ignored in this case
{
std::cout << "Scanner: " << scanner << '\n';
}
};
class Printer: virtual public PoweredDevice // note: PoweredDevice is now a virtual base class
{
public:
Printer(int printer, int power)
: PoweredDevice(power) // this line is required to create Printer objects, but ignored in this case
{
std::cout << "Printer: " << printer << '\n';
}
};
class Copier: public Scanner, public Printer
{
public:
Copier(int scanner, int printer, int power)
: PoweredDevice(power), // PoweredDevice is constructed here
Scanner(scanner, power), Printer(printer, power)
{
}
};
class SuperCopier: public Copier
{
public:
SuperCopier(int scanner, int printer, int power)
: PoweredDevice(power),//This is the line I want to get rid of
Copier(scanner, printer, power)
{
std::cout<<"Super copier constructed\n";
}
};
int main()
{
Copier copier(1,2,3);
SuperCopier superCopier(4, 5, 6);
}
輸出:
PoweredDevice: 3
Scanner: 1
Printer: 2
PoweredDevice: 6
Scanner: 4
Printer: 5
Super copier constructed
爲什麼你想擺脫這條線? – user2393256
我不想離開復雜的類層次結構進一步的開發人員將從複印機繼承他們的新類。當然我的課程更詳細... – ataman
你可能會使用組合而不是繼承... – Jarod42