【问题标题】:C++ inheritance virtual pure functionC++继承虚纯函数
【发布时间】:2015-08-07 02:25:03
【问题描述】:

我在处理以下代码中的继承问题时遇到了问题:

class Animal{
public:
    Animal(int age);
   ~Animal();
    virtual void print();  // problem here     
};

class cat : public Animal
{
public:
    cat(int age);
    ~cat();
    virtual void print();
};
cat::cat(int age) : Animal(age){}
cat::~cat(){}
void cat::print(){
    std::cout<<"I'm a cat "<<"My age is"<<this->getAge()<<std::endl;
}

int main (){
        farm f;
        cat c(3);
        dog d(4);
        f.add(c);
        f.add(d);
        c.print();
        f.print();
        std::cout<<f.getNa()<<std::endl;
        return 0;
    }
farm::farm(){

    this->na=0;
 }
void farm::add(Animal& a){
    if(this->na<10){
    this->ferme.push_back(a);
    this->na+=(*this).na;
    }
    else std::cout<<"la ferme est pleine"<<std::endl;
}
farm::~farm(){}
void farm::remove(){
    this->ferme.pop_back();
}
int farm::getNa(){
    return this->na;
}
void farm::print(){

    for(std::vector<Animal>::iterator it = this->ferme.begin();it !=this-   >ferme.end();++it){
        std::cout<<"test"<<std::endl;
        it->print();
    }

} 当我将print 更改为virtual void print()=0 以拥有纯虚函数时,我遇到了几个编译问题。而当我在Animal 中定义虚函数时,不再考虑cat 的打印函数。 是的 cat::print() 已定义 这里举个例子

这里有几个其他错误 错误: 分配抽象类类型“动物”的对象 ::new ((void*)__p) _Tp(__a0); 对不起,我是新来的

【问题讨论】:

  • cat::print() 定义了吗?
  • Can't reproduceeither case。请始终提供MCVE
  • 如果您能具体说明在 print() 纯虚拟时遇到的错误,这将有所帮助。
  • 我编辑了我的帖子我是新手^^'
  • 你给 dog 添加了 print() 吗?

标签: c++ inheritance virtual


【解决方案1】:

您应该在 cat.cpp 类中定义 virtual void print()。

//Example for cat.cpp class
#include "cat.h"
cat:cat(int age){
cat::age = age;
}
void cat::print(){
std::cout << getAge();

【讨论】:

  • 我这样做了,但是如果我实现 Animal::print() cat::print() 不被考虑,如果我不考虑我有错误 virtual method not implemented 即使我写了 virtual void动物::print()=0
【解决方案2】:

看起来在您的farm 类中,您有一个std::vector&lt;Animal&gt; 类型的成员。您可能认为您在此向量中插入了 catdog 对象,但事实并非如此。如果定义为:

std::vector<Animal> ferme;

那么它只能包含Animal 实例。

这就是为什么如果您将Animal 类设为抽象(将print 设为纯虚拟)它将无法构建。

这也是为什么如果你在Animal 中实现print 方法,它会忽略catdog 中的打印方法。您的farm::print 方法中的it-&gt;print() 调用应用于Animal 实例,因此正确的调用方法是来自Animal 的方法。

虚拟调度机制仅适用于指针或引用,例如:

Animal *a1 = new cat(10);
a1->print(); // will call cat::print()

cat c1(10);
Animal &a2 = c1;
a2.print(); // will call cat::print()

Animal a3 = c1; // like you do when inserting in the vector
a3.print(); // will call Animal::print()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    相关资源
    最近更新 更多