c++ - 无法在赋值中将 'ArithProgression*' 转换为 'Progression*'

标签 c++ inheritance codeblocks dynamic-binding

我定义了一个类“Progression”并将其保存为“Progression.h”,然后我创建了另一个类“ArithProgression”,它扩展了 Progression 类并将其保存为“ArithProgression.h”。

文件:Progression.h

#ifndef PROGRESSION_H
#define PROGRESSION_H
#include <iostream>

using namespace std;

class Progression
{
public:
    Progression()
    {
        cur=first=0;
    }
    Progression(long f)
    {
        cur=first = f;
    }
    void printProgression(int n)
    {
        cout<<firstValue();
        for(int i=0;i<=n; i++)
        {
            cout<<' '<<nextValue();
        }
    }
    virtual ~Progression() {}
protected:
    long first;
    long cur;

    virtual long firstValue()
    {
        cur= first;
        return cur;
    }
    virtual long nextValue()
    {
        return cur++;
    }
};

#endif // PROGRESSION_H

文件:ArithProgression.h

#ifndef ARITHPROGRESSION _H
#define ARITHPROGRESSION _H
#include "Progression.h"
class ArithProgression :public Progression
{
public:
    ArithProgression(long i=1)
    :Progression()
    {
        inc=i;
    }
    virtual ~ArithProgression () {}
protected:
    long inc;
    virtual long nextValue()
    {
        cur+=inc;
        return cur;
    }
private:
};
#endif // ARITHPROGRESSION _H

文件:main.cpp

#include <iostream>
#include "Progression.h"
#include "ArithProgression.h"
using namespace std;
int main()
{
    Progression* p;
    p= new ArithProgression();
    p->printProgression(10);
    delete p;
}

我收到一个错误:代码块 12.11 中“无法将‘ArithProgression*’转换为‘Progression*’”

请帮忙

最佳答案

您发布的代码,works just fine .由于 ArithProgression 确实是 Progression 的子类,所以上面的代码不会触发该错误。

关于c++ - 无法在赋值中将 'ArithProgression*' 转换为 'Progression*',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21163909/

相关文章:

c++ - 被类 vector 混淆 : "The Big Three", 在 push_back 和资源管理之后删除一个类

java - Java中如何覆盖子类中Super对象的某个字段?

c++ - 我应该在初始化列表中调用基类默认构造函数吗?

c++ - GCC 使用旧版本的 C++

c++ - 尝试读取失败后 cin 读数为零

c++ - 当我们 "have to"在循环中将指针传递给某个函数时,如何防止内存泄漏?

c++ - 使用纯 C++/Boost 读取/写入具有 unicode 文件名的文件

javascript - Knockout 中的类继承与方法覆盖

显示构建错误弹出窗口的代码块

c++ - 检查字符串是否为 int 的函数不起作用