#include <iostream>
using namespace std;
class shape
{
public:
shape(int o){r=o;}//这个是叫构造函数吧
virtual void area()=0;//virtual 放在这里对么?
virtual void perimeter()=0;
virtual void volume()=0;
protected:
int r;
};
class circle:virtual public shape
{
public:
circle(int o):shape(o){r=o;}
virtual void area(){cout<<"The area of circle is "<<3.14*r*r<<endl;}
virtual void perimeter(){cout<<"The perimeter of circle is "<<3.14*2*r<<endl;}
virtual void volume(){cout<<"Volume is not defined for circle."<<endl;}
};
class sphere:virtual public circle //这里总是有问题
{
public:
sphere(int o):circle(o){r=o;}
void area(){cout<<"The area of sphere is "<<3.14*4*r*r<<endl;}
void perimeter(){cout<<"Perimeter is not defined for circle."<<endl;}
void volume(){cout<<"The volume of sphere is "<<(4*3.14*r*r*r)/3<<endl;}
};
{
public:
sphere(int o):circle(o),shape(o){r=o;} //在初始化列表中添加初始化shape
void area(){cout<<"The area of sphere is "<<3.14*4*r*r<<endl;}
void perimeter(){cout<<"Perimeter is not defined for circle."<<endl;}
void volume(){cout<<"The volume of sphere is "<<(4*3.14*r*r*r)/3<<endl;}
};
当子类以virtual继承时它只负责构造直接基类,间接基类不会被父类构造,所以必须自己手动添加追问
那还有别的方法么,还有能说下你的qq么 希望大神能指点指点
追答还有一种方法就是给shape类添加无参的构造函数,这样在sphere类构造的时候就会调用shape的无参构造函数
class shape
{
public:
shape(int o){r=o;}//这个是叫构造函数吧
shape(){} //无参构造函数
virtual void area()=0;//virtual 放在这里对么?
virtual void perimeter()=0;
virtual void volume()=0;
protected:
int r;
};