假设我有几个带有 C 风格构造函数的对象:
struct MyStruct { int item1; int item2 };
MyStruct construct_struct(int a, int b, int c, ...);
我想在不完全重新安排代码复制和粘贴重复代码的情况下,简单地在结构下定义一个 C++ 样式的构造函数:
MyStruct::MyStruct(int a, int b, int c, ...){
// in pseudo code
this = construct_struct(a,b,c,...);
}
这在 C++ 中如何完成?
最佳答案
I would like, without totally rearranging code copying and pasting duplicate code, to simply define beneath the structures a C++ style constructor
与其复制代码,不如将其移动到 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 构造函数。
关于C++:通过构造函数中的返回构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174046/