无法在c++中实例化抽象类

Cannot instantiate abstract class in C++ error

本文关键字:实例化 抽象类 c++      更新时间:2023-10-16

我想在"Dog"类中实现一个接口,但是我得到了以下错误。最后一个目标是使用一个接收可比较对象的函数,这样它就可以将对象的实际实例与我通过参数传递的对象进行比较,就像一个等号一样。Operator重载不是一个选项,因为我必须实现那个接口。当使用"new"关键字创建对象时触发错误。

"错误2错误C2259: 'Dog':无法实例化抽象类c:usersfenixdocumentsvisual studio 2008projectsinterface-testinterface-testinterface-test.cpp 8 "

下面是相关类的代码:

#pragma once
class IComp
{
    public:
        virtual bool f(const IComp& ic)=0; //pure virtual function
};
    #include "IComp.h"
class Dog  : public IComp
{
    public:
        Dog(void);
        ~Dog(void);
        bool f(const Dog& d);
};
#include "StdAfx.h"
#include "Dog.h"
Dog::Dog(void)
{
}
Dog::~Dog(void)
{
}
bool Dog::f(const Dog &d)
{
    return true;
    }
#include "stdafx.h"
#include <iostream>
#include "Dog.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    Dog *d = new Dog; //--------------ERROR HERE**
    system("pause");
        return 0;
}

bool f(const Dog &d)不是bool f(const IComp& ic)的实现,因此虚拟bool f(const IComp& ic)仍然不是由Dog实现的

你的类Dog没有实现方法f,因为它们有不同的签名。它也需要在Dog类中声明为:bool f(const IComp& d);,因为bool f(const Dog& d);完全是另一个方法。

    bool f(const Dog& d);

不是IComp

的实现
    virtual bool f(const IComp& ic)=0; //pure virtual function

你对Dogf的定义实际上是隐藏了纯虚函数,而不是实现它。