C ++抽象类参数错误解决方法 [英] C++ abstract class parameter error workaround

查看:136
本文介绍了C ++抽象类参数错误解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码段会产生错误:

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;  

virtual void print() = { }

我希望能够通过使用多态性(即A* x = new B() ; test(x);)将扩展/实现基类A的任何类作为参数传递

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); )

欢呼

推荐答案

由于您无法实例化一个抽象类,因此按值传递一个抽象类几乎可以肯定是一个错误.您需要通过指针或引用来传递它:

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) ...

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.

这篇关于C ++抽象类参数错误解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆