繁体   English   中英

如何在子类中初始化静态常量成员变量?

[英]How do I initialize static constant member variables in a subclass?

我正在尝试制作一个模板,它可以制作几种不同类型的类,主要区别在于物体名称,即电阻器应输出“电阻:4欧姆”,其中电容器输出“电容:4法拉”相同的函数调用,没有重载。 理想情况下,单位只是静态const std :: string值。

我的方法是使基类未初始化

这里的问题是现在我必须在所有子类中重载所有不同类型的构造函数。

有没有办法初始化子类中的静态const变量?

谢谢

当前标准不允许在派生类构造函数内初始化基类的public/protected成员。 人们必须依靠其他技术来实现它。 有两种方法可以解决您的问题。

(1)声明virtual方法返回std::string以获取适当的标签/值。 但是,这会导致不必要的开销。 从您的实现中我可以看出您想要避免它。

(2)使用中间template类,它将为您完成。

enum eValue { OHM, FARAD, AMP };  // enum to string mapping 
static const string sValue[] = { "ohm", "farad", "amp" };

// make the 'value' as reference string; to avoid making multiple copies
class Base {
  Base (const string &v) : value(v) {}
public:  const string &value; // has to be accessed using object
};

template<eValue TYPE>
struct Link : Base {  // this is an intermediate class for every derived
  Link () : Base(sValue[TYPE]) {}
};

class Resistance : public Link<OHM> {
};

CRTP可能会有所帮助:

class CircuitElement
{
    virtual const std::string& getLabel() const = 0;
    virtual const std::string& getUnit() const = 0;
};

template <typename ElementType>
class CircuitElementBase : public CircuitElement
{
public:
    const std::string& getLabel() const { return ElementType::Label; }
    const std::string& getUnit() const { return ElementType::Unit; }
};

class Resistor : public CircuitElementBase<Resistor>
{
    static std::string Label, Unit;
};

std::string Resistor::Label("Resistance: ");
std::string Resistor::Unit("ohm");

取决于你的要求我想:

#include <string>
#include <iostream>
#include <sstream>

struct ResistorDescriptor
{
    static const std::string type;
    static const std::string unit;
};

const std::string ResistorDescriptor::type = "Resistance";
const std::string ResistorDescriptor::unit = "ohm";

struct CapacitorDescriptor
{
    static const std::string type;
    static const std::string unit;
};

const std::string CapacitorDescriptor::type = "Capacitance";
const std::string CapacitorDescriptor::unit = "farad";

template <class T>
class Element
{
public:
    Element(int val) : value(val) {}

    std::string output()
    {
        std::stringstream s;
        s << T::type << ": " << value << " " << T::unit << std::endl;
        return s.str();
    }

private:
    int value;
};

int main(int argc, char** argv)
{
    Element<ResistorDescriptor> resistor(4);
    Element<CapacitorDescriptor> capacitor(5);

    std::cout << resistor.output() << capacitor.output() << std::flush;

    return 0;
}

输出:

Resistance: 4 ohm
Capacitance: 5 farad

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM