0

Let's say I am creating a tree, and I have a class of Node and a class of Cars.

   class Cars : public Node{
     ....
    };

If I have an object all ready defined as a Node, but I now want it to make it a Car as well, how would I do it?

Thank you !

4

1 回答 1

0

您可以做的最接近的事情是为您的Cars类提供一个转换构造函数并创建一个新实例:

class Node
{
    // stuff goes here
};

class Cars : public Node
{
public:
    // other constructors, destructor, members, etc.
    Cars(const Node& node)
    {
        // copy node data into the Node portion of the car
    }
};

int main()
{
    Node n;
    Car c(n);
    return 0;
}

如果您首先创建它Node,则无法在不创建实际实例并将数据复制到其中的情况下神奇地将其更改为 a 。CarCar

于 2013-10-27T04:17:08.867 回答