代码之家  ›  专栏  ›  技术社区  ›  Ikaso

如何正确避免CS2512

  •  0
  • Ikaso  · 技术社区  · 16 年前

    请帮我解决以下问题:

    我有以下课程:

    class ChemicalElement
    {
    private:
        std::string _name;
        void Init(const std::string& name);
    public:
        ChemicalElement(const std::string& name);
        ChemicalElement(const ChemicalElement& ce);
    };
    
    class CombinationRule
    {
    private:
        ChemicalElement _ce1;
        ChemicalElement _ce2;
        void Init(const ChemicalElement& ce1, const ChemicalElement& ce2);
    public:
        CombinationRule(const ChemicalElement& ce1, const ChemicalElement& ce2);
        CombinationRule(const CombinationRule& rule);
    };
    

    实施是显而易见的。我打算使用init方法初始化CombinationRule,以最小化代码重复。唉,如果我不在每个构造函数中使用“成员初始化列表”,编译器会抱怨“错误C2512:'ChemicaleleElement':没有合适的默认构造函数可用”。是否有一种优雅的方法来解决这个错误,而不是使用默认的构造函数或成员初始化列表? 顺便说一句:如果类定义中还有其他问题,请添加它。因为我正在重读C++,所以我想知道它们。

    4 回复  |  直到 16 年前
        1
  •  3
  •   Kirill V. Lyadvinsky    16 年前

    应该实现的构造函数 CombinationRule 因此,他们将使用 ChemicalElement :

    CombinationRule::CombinationRule(const ChemicalElement& ce1, 
      const ChemicalElement& ce2) : _ce1(ce1), _ce2(ce2) 
    { 
      ... 
    }
    
    CombinationRule::CombinationRule(const CombinationRule& rule) : 
      _ce1( rule._ce1 ), _ce2( rule._ce2 )
    {
      ...
    }
    
        2
  •  1
  •   Jeremy Friesner    16 年前

    如果要在任何类型的数组或容器中使用该类的对象,我认为需要在定义任何其他构造函数的任何类中放置默认构造函数。但是,默认构造函数的实现可以只是一个空的/无操作方法。

    您不需要放入成员初始化列表(尽管在某些情况下使用成员初始化列表更有效,因为这样您的成员变量只初始化一次,而不是通过其默认构造函数初始化一次,然后通过init()方法写入第二次)。

        3
  •  1
  •   David Stocking    16 年前

    我想你想要这个

    ChemicalElement * ce1;
    

    我这么说是因为我认为它试图根据组合规则运行默认的构造函数,而反过来需要为ce1和ce2获得一个化学元素…但我可能错了。

    很肯定,krill的方法是为一个特定的构造函数指定一个变量的构造函数,但是我说了f,并做了这个,所以ce1不需要由编译器构造:)

        4
  •  1
  •   ima    16 年前

    在这个特定的例子中,我将继续重复(它只是写两个初始值设定项,没有什么可困扰的)。

    但是假设实际情况更复杂:使用OO工具避免代码重复。

    class CombinationRule : public ElementPair ...

    class Combination { ElementPair twoElements; ...}

    其中elementPair包含两个化学元素和一个构造函数(带有公共代码),组合规则构造函数使用elementPair的构造函数初始化。

    还有其他方法:用一些invalidChemicaleleElement实例初始化成员,或者使用invalidChemicaleElement的空指针(auto-ptr)。

    推荐文章