您好,我是 C++ 新手,在使用以下代码时遇到问题:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void area() = 0;
virtual void perimeter() = 0;
virtual void volume() = 0;
};
class Circle : public Shape
{
protected:
int r;
public:
Circle()
{
r = 0;
}
Circle(int num)
{
r = num;
}
void area()
{
double area = (r * r) * (3.14);
cout << "The area of the circle = " << area << endl;
}
void perimeter()
{
double perimeter = 2 * (3.14) * r;
cout << "The circumference of the circle = " << perimeter << endl;
}
void volume()
{
cout << "You are tapping into another dimension. AHHH Error!" << endl;
}
};
class Sphere : public Circle
{
protected:
int r;
public:
Sphere() :Circle()
{
r = 0;
}
Sphere(int num) : Circle(num)
{
r = num;
}
void area()
{
double area = 4 * (3.14) * (r * r);
cout << "The surface area of the sphere = " << area << endl;
}
void perimeter()
{
double perimeter = 2 * (3.14) * r;
cout << "The circumference of the sphere = " << perimeter << endl;
}
void volume()
{
double volume = ((4 / 3) * (3.14) * (r * r * r));
cout << "The volume of the sphere = " << volume << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Shape *ptr;
Circle c1(5);
Circle c2();
Sphere sp1(6);
Sphere sp2();
ptr = &c1;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &c2;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &sp1;
ptr->perimeter();
ptr->area();
ptr->volume();
ptr = &sp2;
ptr->perimeter();
ptr->area();
ptr->volume();
return 0;
}
控制台告诉我这个:
error C2440: '=' : cannot convert from 'Circle (__cdecl *)(void)' to 'Shape *'
error C2440: '=' : cannot convert from 'Sphere (__cdecl *)(void)' to 'Shape *'
注意: 我在包含以下内容的行中收到这些错误:“ptr = &c2;”和“ptr = &sp2;”
这仅适用于使用不带参数的构造函数的实例。
带参数的构造函数出于某种原因工作??
你能帮忙的话,我会很高兴。谢谢!!!
最佳答案
使用无参数构造函数构建对象的正确方法是
Circle c2;
不是
Circle c2();
后一行是函数声明。
关于使用从抽象类继承的 C++ 默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594658/