如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
How to make working variadic arguments method inheritance with same method overloaded on child class
以下代码工作:
class Test_Interface {
public:
template<typename... Args>
void Split(int weight, Args... args){
Split(weight);
Split(args...);
}
virtual void Split(int weight) {
std::cout << "Test_Interface::Split weight: " << weight << std::endl;
};
};
class Test : public Test_Interface {};
int main()
{
Test test;
test.Split(1, 20, 300);
}
但是,如果我定义了 split in test 类中的超载,则如下:
class Test : public Test_Interface {
public:
virtual void Split(int weight) {
std::cout << "Test::Split weight: " << weight << std::endl;
};
};
然后我会收到错误:错误:呼叫'test :: split(int,int,int)'
没有匹配函数我知道,如果我还定义了类 test test 中的variadic参数方法:
class Test : public Test_Interface {
public:
template<typename... Args>
void Split(int weight, Args... args){
Split(weight);
Split(args...);
}
virtual void Split(int weight) {
std::cout << "Test::Split weight: " << weight << std::endl;
};
};
它再次工作,但它不做一开始就打算做的事情,它只有一个位置(界面),其中定义的variadic参数方法,并且只有每个派生的类仅使用非variadic方法的自定义实现。我的目标是避免一遍又一遍地复制相同的代码,并在多个位置维护。为什么当儿童课不超载方法后,该方法继承起作用?有没有办法在不复制的情况下进行操作?谢谢
当您声明Test::Split
函数时,您 hide 继承的函数。之后,当您在Test
对象上使用Split
时,编译器只知道Test::Split
而不是父母Test_Interface::Split
功能。
解决方案很容易:您将符号从父级将符号拉入Test
类:
class Test : public Test_Interface {
public:
using Test_Interface::Split; // Pull in the Split symbol from the parent class
virtual void Split(int weight) {
std::cout << "Test::Split weight: " << weight << std::endl;
};
};
相关文章:
- 使用非递归插入方法实现 AVL 树
- C++方法实现:是否可以避免每次都键入类名?
- 如何使用吸气剂方法实现C++封装
- 在C++中使用克隆方法实现多晶型效果
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 双向链表插入方法实现 - 正在搜索哪个节点
- 没有虚拟调度的默认方法实现
- C 构造函数和方法实现
- C :如何使用相同的数据类使用不同的方法实现
- 将同一类的方法实现放在不同的对象文件中
- 私有方法实现编译错误
- 使用公共命名方法实现非公共赋值运算符
- 使用 SFINAE 在 Clase 模板中选择不同的方法实现
- 如何根据方法实现的声明顺序对其进行排序
- 使用一个方法实现不同类型赋值的优雅方式,并且没有警告
- 在运行时选择方法实现
- 将参数传递给c++ CORBA方法实现
- 静态constexpr方法实现导致GCC错误
- 包括c++中的头文件(类定义和方法实现)
- 如何在swig生成的代理类中更改特定的方法实现