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

标签 c++ oop

假设我有几个带有 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/

相关文章:

r - 定义调用 R6 对象之外的其他方法的方法

Python 和 OO 编程(类属性和派生类)

c++ - 错误 : ‘logFileObj’ does not name a type

c++ - 如何打印调试 C++ Win32 DLL?

c++ - 如何使用旋转编码器控制HID设备?

php - 避免在 PHP 中使用访问修饰符的原因

oop - 中间类 : add getter-setter support for properties

类似 C++ 的 Moose 与 Perl 的 OOP 用法

c++ - 尝试使用 CLion 使用 .C 和 .CPP 文件构建项目时出现未定义的引用错误

c++ - ClassName::method() 是不是意味着调用了ClassName的成员函数method()?