Constructor Overloading in C++

前端 未结 5 2020
慢半拍i
慢半拍i 2020-12-13 18:28

My C++ overloading does not act as I assume it should:

#include \"Node.h\"
#include 

Node::Node()
{
    cout << \"1\" << endl;
          


        
5条回答
  •  旧巷少年郎
    2020-12-13 19:05

    Node(Game(),v); in your constructor doesn't do what you expected. It just creates a temporary without using it and makes no effect. Then it immediately destructs that temporary when control flows over the ;.

    The correct way is initializing the members in each constructor. You could extract their common code in a private init() member function and call it in each constructor like the following:

    class Foo {
        public:
            Foo(char x);
            Foo(char x, int y);
            ...
        private:
            void init(char x, int y);
    };
    
    Foo::Foo(char x)
    {
        init(x, int(x) + 3);
        ...
    }
    
    Foo::Foo(char x, int y)
    {
        init(x, y);
        ...
    }
    
    void Foo::init(char x, int y)
    {
        ...
    } 
    

    C++11 will allow constructors to call other peer constructors (known as delegation), however, most compilers haven't supported that yet.

提交回复
热议问题