假设我有几个带有C风格构造函数的对象:
struct MyStruct { int item1; int item2 };
MyStruct construct_struct(int a, int b, int c, ...);
Run Code Online (Sandbox Code Playgroud)
我想,在没有完全重新排列代码复制和粘贴重复代码的情况下,只需在结构下面定义一个C++样式构造函数:
MyStruct::MyStruct(int a, int b, int c, ...){
// in pseudo code
this = construct_struct(a,b,c,...);
}
Run Code Online (Sandbox Code Playgroud)
如何在C++中完成?
我想,在没有完全重新排列代码复制和粘贴重复代码的情况下,只需在结构下面定义一个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, ...);
}
Run Code Online (Sandbox Code Playgroud)
这解决了代码重复的问题,并保留了C构造函数.