您可以声明会员功能并使他们做不同的事情吗?
Can you declare a member function and make them do different things?
我已经尝试了多种方法来解决这个问题,但是它们都没有起作用。我要实现的是。
我有这样的课程。
class Auton {
public:
int slot;
const char * name;
void run();
};
我想做的是使run
函数做不同的事情。例如 -
// The code below doesn't work, unfortunately :(
Auton one;
void one::run() {
// Do something here
}
Auton two;
void two::run() {
// Do something different here
}
这是可能的吗?
可以使用lambda表达式。
示例:
class Auton {
public:
int slot;
const char * name;
std::function<void()> run;
};
Auton one;
one.run = [] {
// Do something here
};
Auton two;
two.run = [] {
// Do something different here
};
不幸的是。可能的是:
class Auton {
public:
// ...
virtual void run();
};
class AutonOne : public Auton {
public:
// ...
void run() override
{
// Do something
}
};
class AutonTwo : public Auton {
public:
// ...
void run() override
{
// Do something different
}
};
AutonOne one;
AutonTwo two;
在此处了解有关此信息的更多信息:为什么我们需要C ?
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 函数向量_指针有不同的原型,我可以构建一个吗
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- #为""定义宏;静态";针对不同的上下文
- 大小相等但成员数量不同的结构之间的性能差异
- c++类声明时,相同的例程,不同的成员变量类型
- 通过组合不同的类型来创建唯一的id
- 在Linux和C++中的Windows上,散列字符串值会产生不同的输出
- 不同的Visual Studio版本中缺少.dll
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 使用不同的链接器会产生不同的机器代码吗
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- DrawIndexedInstanced 具有不同的 Index Count per Instance (Directx
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 为什么C++有不同的变量初始化方式?
- C++:告诉用户输入 A、B 或 C,但如果他们输入不同的字符怎么办?
- 您可以声明会员功能并使他们做不同的事情吗?