Constructor Overloading in C++

前端 未结 5 2018
慢半拍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:13

    Node::Node(double v)
    {
        cout << "2" << endl;
        Node(Game(),v);            // 1      
    }
    
    1. Creates a nameless object, which does not persist beyond that expression. So, it is not affecting the original object's value upon which the single argument constructor is instantiated. You also need to understand that this temporary object is entirely different from the original constructing object.

    However you can extend the life time of this temporary object by a const reference i.e.,

    Node::Node(double v)
    {
        cout << "2" << endl;
        const Node& extendTemporay = Node(Game(),v); 
    
        value = extendTemporary.value ;  // Just trivial example;
                                         // You can simply do it by value = v;               
    }
    

提交回复
热议问题