gpt4 book ai didi

c++ - 为什么要在子派生类中构造虚基?

转载 作者:行者123 更新时间:2023-11-28 05:22:45 26 4
gpt4 key购买 nike

为什么我必须在 SuperCopier 的构造函数中调用 PoweredDevice? Copier 的构造函数在直接创建 Copier 对象时已经初始化。

有没有简单的方法封装Copier? (只使用它的构造函数而不关心它的基础。)

以下代码来自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

最佳答案

有了组合,你可能会做

class PoweredDevice
{
public:
explicit PoweredDevice(int power)
{
std::cout << "PoweredDevice: " << power << '\n';
}
};

class Scanner
{
public:
Scanner(PoweredDevice& powerDevice, int scanner)
: poweredDevice(powerDevice)
{
std::cout << "Scanner: " << scanner << '\n';
}
private:
PoweredDevice poweredDevice
};

class Printer
{
public:
Printer(PoweredDevice& powerDevice, int printer)
: poweredDevice(powerDevice)
{
std::cout << "Printer: " << printer << '\n';
}
private:
PoweredDevice poweredDevice
};

class Copier: public PoweredDevice, public Scanner, public Printer
{
public:
Copier(int scanner, int printer, int power)
: PoweredDevice(power),
Scanner(*this, scanner),
Printer(*this, printer)
{
}
};

class SuperCopier: public Copier
{
public:
SuperCopier(int scanner, int printer, int power)
: Copier(scanner, printer, power)
{
std::cout<<"Super copier constructed\n";
}
};

关于c++ - 为什么要在子派生类中构造虚基?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com