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

C++:通过构造函数中的返回构造

  •  2
  • Chris  · 技术社区  · 6 年前

    假设我有几个具有C风格构造函数的对象:

    struct MyStruct { int item1; int item2 };
    MyStruct construct_struct(int a, int b, int c, ...);
    

    MyStruct::MyStruct(int a, int b, int c, ...){   
        // in pseudo code
        this = construct_struct(a,b,c,...);
    }
    

    如何做到这一点在C++?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Sergey Kalinichenko    6 年前

    我希望,在不完全重排代码复制和粘贴重复代码的情况下,简单地定义结构下面的C++风格构造函数。

    不是复制代码,而是将它移到C++构造函数中,然后重写C样式构造函数,调用C++。

    MyStruct::MyStruct(int a, int b, int c, ...){   
        // the code from construct_struct(a,b,c,...) goes here
    }
    
    MyStruct construct_struct(int a, int b, int c, ...) {
        return MyStruct(a, b, c, ...);
    }
    

    这解决了代码重复的问题,并保留了C构造函数。

        2
  •  1
  •   StoryTeller - Unslander Monica    6 年前

    suggested (尽管你应该这样做)。中的方法 your own answer 只要您的对象是可分配的,也可以工作。对于你的目标不太可能得到 const 成员,或由于另一个原因无法分配,我提出这个完整性。

    您可以委托给复制/移动构造函数:

    MyStruct construct_struct(int a, int b, int c, ...){
    }
    
    MyStruct::MyStruct(int a, int b, int c, ...) : MyStruct(construct_struct(a,b,c,...)) {}
    
        3
  •  0
  •   Chris    6 年前

    答案很简单:

    MyStruct construct_struct(int a, int b, int c, ...){
    }
    MyStruct::MyStruct(int a, int b, int c, ...){
        *this = construct_struct(a,b,c,...);
    }