c++ - 如何根据初始化参数修复类函数行为
问题描述
我正在创建一个 C++ 类,它在初始化期间采用某些参数,并具有一些基于其私有变量的函数,类似于compute
这里的函数:
class A {
public:
A(int x){
a = x;
}
int compute(int y){
if (a == 0){
return y*y;
}
else if (a == 1){
return 2*y;
}
else{
return y;
}
}
private:
int a;
};
// usage
A myA(1); // private variables set only once
myA.compute(10); // this will check value of a
myA.compute(1); // this will check value of a
鉴于私有变量在初始化期间设置并且不会再次更改,有没有什么有效的方法可以避免在运行时与私有变量相关的条件检查?
感谢您提供任何和所有帮助。谢谢
解决方案
如果您将使用例如函数对象作为成员,则可以避免条件检查,并根据变量 a 的值进行设置。无论如何,我认为条件检查不会是大的性能问题。但这当然取决于您的应用程序。
#include <functional>
#include <iostream>
class A {
public:
A(int x)
: a { x }
{
if (a == 0){
compute = [](int y){ return y*y; };
}
else if (a == 1){
compute = [](int y){ return 2*y; };
}
else{
compute = [](int y){ return y; };
}
}
std::function<int(int)> compute;
private:
int a;
};
// usage
int main()
{
A myA(1); // private variables set only once
std::cout << myA.compute(10) << std::endl;
std::cout << myA.compute(1) << std::endl;
return 0;
}
推荐阅读
- c++ - 我可以强制提升在 Windows 上更喜欢正斜杠吗?
- odoo - 如何从 Odoo13 中的自定义模块生成发票?
- c - 有没有办法在没有所有重复 if 语句的情况下完成以下循环?
- json - 在角度2+的连接方法中插入html标签不起作用
- python - Python-为什么即使我输入了应该可以使用的密码,它也会说密码被拒绝?
- swift - 从剪贴板快速粘贴音频文件(.mp3、.m4a 等)并保存
- java - 无法将 Mpesa Api 集成到我的 Android 应用程序中
- node.js - 如何访问使用混合类型模式的 mongoose 查询的 mongodb 数据中的每个字段值
- python - 有机会的记号
- reactjs - ReactNative & Expo:离子不渲染