是否有快捷方式编写具有相同定义但原型不同的函数?

发布于 2025-01-21 13:46:27 字数 377 浏览 3 评论 0原文

我有一种基本上看起来像这样的类的方法:

void MyClass::method() {
    // Here I'm just doing something with parameters which are class attributes
    parameter_3 = parameter_1 + parameter_2
}

我需要另一种方法,它具有完全相同的主体,但是现在我希望通过函数调用传递参数:

void MyClass::method(type1_t parameter_1, type2_t parameter_2);

我不想重复相同的代码另一个定义。有什么可能的解决方案?越少越好。

I have a method of a class which basically looks like this:

void MyClass::method() {
    // Here I'm just doing something with parameters which are class attributes
    parameter_3 = parameter_1 + parameter_2
}

I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call:

void MyClass::method(type1_t parameter_1, type2_t parameter_2);

I do not want to repeat the same code in another definition. What are possible solutions? The less ugly the better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤星 2025-01-28 13:46:27

我需要另一个具有完全相同的物体的方法,但是现在我希望参数通过函数调用传递:

可以使用委托来解决这一点。只需从另一个调用一个过载即可。例子:

void MyClass::method(type1_t parameter_1, type2_t parameter_2) {
    parameter_3 = parameter_1 + parameter_2;
}

void MyClass::method() {
    method(parameter_1, parameter_2);
}

I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call:

This can be solved using delegation. Simply call one overload from the other. Example:

void MyClass::method(type1_t parameter_1, type2_t parameter_2) {
    parameter_3 = parameter_1 + parameter_2;
}

void MyClass::method() {
    method(parameter_1, parameter_2);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文