C++ abstract class parameter error workaround

别来无恙 提交于 2020-01-02 00:54:24

问题


The code snippet below produces an error:

#include <iostream>

using namespace std;

class A
{

public:

  virtual void print() = 0;
};

void test(A x) // ERROR: Abstract class cannot be a parameter type
{
  cout << "Hello" << endl;
}

Is there a solution/workaround for this error other/better than replacing

virtual void print() = 0;  

with

virtual void print() = { }

EDIT: I want to be able to pass any class extending/implementing the base class A as parameter by using polymorphism (i.e. A* x = new B() ; test(x); )

Cheers


回答1:


Since you cannot instantiate an abstract class, passing one by value is almost certainly an error; you need to pass it by pointer or by reference:

void test(A& x) ...

or

void test(A* x) ...

Passing by value will result in object slicing, with is nearly guaranteed to have unexpected (in a bad way) consequences, so the compiler flags it as an error.




回答2:


Of course, change the signature:

void test(A& x)
//or
void test(const A& x)
//or
void test(A* x)

The reason your version doesn't work is because an object of type A doesn't logically make sense. It's abstract. Passing a reference or pointer goes around this because the actual type passed as parameter is not A, but an implementing class of A (derived concrete class).



来源:https://stackoverflow.com/questions/11422070/c-abstract-class-parameter-error-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!