c++ - 派生节点类

标签 c++

我有基类、派生类,然后是派生自派生类的节点类。通常,我会做 struct Node,其中我有 Object 对象(作为节点中的数据)。但是,在派生 Node 类的情况下,这没有任何意义,因为已经调用了 Derived 的构造函数。所以,我的问题是 - 如何将数据分配给节点?

class Base
{
    payload;
};

class Derived : public Base
{
    payload;
};

class Node : public Derived
{
    Node(Object & object);
    /*
    Previously I'd have struct with Object object_, and I 
    would do object = object_ (which would call an overload to
    make a deep copy). But, in this case we already have an instance 
    of Derived, and making another one doesn't seem right. 
    So, my question is to how access that instance to assign 
    passed object to it? Or am I doing something completely stupid?
    */
}

最佳答案

您可以类型转换(类到类)或复制构造函数

class Node : public Derived
{
        public:
                Node() {
                }
                /** type conversion operator **/
                operator Derived() {
                        /**  code **/
                }
                /** copy constructor **/
                Node(Node &nd_obj) : Derived(Derived d_obj){    
                        cout<<"Node copy const called "<<endl;
                        cout<<"payload = "<<nd_obj.payload<<endl;
                }
};
int main() {
        Derived d1;
        Node Nd1;
        d1 = Nd1;//type conversion

        Node Nd2 = d1;//copy constructor, make sure exact match is there

}

关于c++ - 派生节点类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258281/

相关文章:

c# - 在与 STL 混合的 C# 中调用非托管 C++ 代码

c++ ->= 和 <= 没有按照我使用它们的方式工作,我哪里搞砸了?

c++ - 为什么 C++ 函数模板在其签名中包含返回类型

c++ - 使用 GCC 程序集向左/向右旋转移动次数

c++ - argc 和 argv 的 void cast

c++ - boost::进程间共享内存

c++ - 为什么顺序容器同时具有 size_type 和 difference_type?

c++ - 通过右值引用返回更有效率吗?

c++ - 如何在作用域指针类中正确使用动态分配的不透明指针?

c++ - 两个日期之间的秒数差异?