C ++抽象类不能有一个具有该类的参数的方法 [英] C++ Abstract class can't have a method with a parameter of that class

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

问题描述

我创建了这个.h文件

  #pragma once 

命名空间Core
{
class IComparableObject
{
public:
virtual int CompareTo(IComparableObject obj)= 0;
};但是编译器不喜欢 IComparableObject obj param(); 如果方法是virtual pure,而

  virtual int CompareTo(IComparableObject obj){} 

没关系,但是我想把它作为虚拟纯。我该如何设法呢?是否可能?

解决方案

您尝试通过值传递 obj 。您不能通过值传递抽象类实例,因为任何抽象类都不能被直接实例化。要做你想要的,你必须通过引用传递 obj ,例如:

  virtual int CompareTo(IComparableObject const& obj)= 0; 

它适用于 CompareTo 因为那样的类不再抽象了。但请注意,发生切片!您不希望通过值传递 obj


I created this .h file

#pragma once

namespace Core
{
    class IComparableObject
    {
    public:
            virtual int CompareTo(IComparableObject obj)=0;
    };
}

But compiler doesn't like IComparableObject obj param if the method is virtual pure, while

virtual int CompareTo(IComparableObject obj) {}

It's ok, however I want it as virtual pure. How can I manage to do it? Is it possible?

解决方案

You are trying to pass obj by value. You cannot pass an abstract class instance by value, because no abstract class can ever be instantiated (directly). To do what you want, you have to pass obj by reference, for example like so:

virtual int CompareTo(IComparableObject const &obj)=0;

It works when you give an implementation for CompareTo because then the class is not abstract any longer. But be aware that slicing occurs! You don't want to pass obj by value.

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

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