我定义了一个类“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/