[英]Overloading member function of base class with other derived classes C++
How can I fix this code?我该如何修复此代码? The error that I'm getting is "undefined reference to 'vtable for base' " The doSomething function should be pure if possible.
我得到的错误是“未定义对 'vtable for base' 的引用” 如果可能的话,doSomething 函数应该是纯函数。
Example:例子:
class A{
};
class A_A : public A{
};
class A_B : public A{
};
class A_C : public A{
};
/////////////////////////////////////
class base{
public:
virtual void doSomething(A* );
//virtual void doSomething(A* ) = 0; //or...
};
class derived : public base{
public:
void doSomething(A_A* );
void doSomething(A_B* );
void doSomething(A_C* );
};
By adding the =0
at the back you are forcing the derived class to override the function.通过在后面添加
=0
,您将强制派生类覆盖该函数。 This solves the issue:这解决了这个问题:
class base{
public:
virtual void doSomething(A*a) = 0;
};
class derived : public base{
public:
// you can pass any derived class of A to this function
// mark as override suggested by Omid CompSCI for clarity
void doSomething(A*a) override { }
};
I hope that this helps.我希望这个对你有用。 Also you shouldn't create 3 different versions of doSomething for each of the derived classes of A because this defeats the purpose of having all those classes inherit from A.
此外,您不应该为 A 的每个派生类创建 3 个不同版本的 doSomething,因为这违背了让所有这些类继承自 A 的目的。
Also consider using smart pointers because they will handle memory dealocation for you.还可以考虑使用智能指针,因为它们会为您处理内存释放。 Check out this question.
看看这个问题。 This is how I would approach this:
这就是我将如何处理这个:
#include<iostream>
#include<memory>
class A
{
public:
virtual void print() = 0;
};
class A1: public A
{
public:
void print() override {std::cout << "A1" << std::endl;}
};
class A2: public A
{
public:
void print() override {std::cout << "A2" << std::endl;}
};
class A3: public A
{
public:
void print() override {std::cout << "A3" << std::endl;}
};
class base
{
public:
virtual void action(std::shared_ptr<A>) = 0;
};
class derived: public base
{
public:
// this way you can have a generic function which will handle each one of the derived classes of A.
void action(std::shared_ptr<A> a) override { a->print(); }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.