注册 登录
编程论坛 C++教室

谁能告诉我错误怎么改==

Orphan 发布于 2015-05-29 21:02, 528 次点击
/*求球,圆柱,圆锥的体积和面积*/
#include<iostream>
using namespace std;
const double Pi=3.14;
class ball
{protected:
int r;
public:
voidsetdata()
   {
    cout<<"please enter the r:"<<endl;
    cin>>r;
   }
intgetR()
   {
    return r;
   }
double volume()
   {
double v;
     v=4/3*Pi*getR()*getR()*getR();
    return v;
   }
};
classyuan : public ball
{private:
int h;
public:
void input()
   {
    setdata();
    cout<<"please enter the h:"<<endl;
    cin>>h;
   }
double volume()
   {
double v;
     v=Pi*getR()*getR()*h;
    return v;
   }
};
classzhui : public yuan
{public:
void input()
   {
    setdata();
   }
double volume()
   {
double v;
     v=1/3*Pi*getR()*getR()*h;
    return v;
   }
private:

};
int main()
{
ball b;
b.setdata();
cout<<"the volume of ball is:"<<endl;
cout<<b.volume();
yuan y;
y.input();
cout<<"the volume of yuan is:"<<endl;
cout<<y.volume();
zhui z;
z.input();
cout<<"the volume of zhui is:"<<endl;
cout<<z.volume();
return 0;

}


E:\\jiue\jiejie.cpp(50) : error C2248: 'h' : cannot access private member declared in class 'yuan'
        E:\\jiue\jiejie.cpp(26) : see declaration of 'h'
执行 cl.exe 时出错.

jiue.exe - 1 error(s), 0 warning(s)
6 回复
#2
林月儿2015-05-29 21:45
#include<iostream>
using namespace std;
const double Pi=3.14;
class yuan{
    protected:
      int r;
    public:
      void setdata(){
         cout<<"\nplease enter the r:"<<endl;
         cin>>r;
     }
     int getR(){
          return r;
     }
     double getArea(){
         return Pi*r*r;
    }
};
class  ball: public yuan{
  public:
     void input(){
         setdata();
    }
    double volume(){
        double v;
        v=4*Pi*getR()*getR()*getR()/3;
        return v;
   }
};
class zhui : public yuan{
    public:
      void input(){
         setdata();
         cout<<"please enter the h:"<<endl;
         cin>>h;
      }
      double volume(){
         double v;
         v=getArea()*h/3;
         return v;
      }
    private:
      int h;
};
int main(){
yuan y;
cout<<"yuan :";
y.setdata();
cout<<"the area of yuan is:"<<endl;
cout<<y.getArea()<<endl;
zhui z;
cout<<"zhui";
z.input();
cout<<"the volume of zhui is:"<<endl;
cout<<z.volume()<<endl;
ball b;
cout<<"ball";
b.input();
cout<<"the volume of ball is:"<<endl;
cout<<b.volume()<<endl;
return 0;
}
#3
yangfrancis2015-05-29 23:40
楼主的yuan类里面的h成员为私有,不能被派生类调用的,一定是因为zhui类的Input函数和volume函数调用了h才导致报错。试试把yuan类的h改成protected看成不成。另外注意一下,你的zhui类继承了Input函数,但又另写了一个,有可能会让你输入两次半径哦。
#4
Orphan2015-05-30 13:23
回复 3楼 yangfrancis
对的,我一开始没写圆锥时调试时就要输入两次半径= =。那现在圆锥那部分要继承哪一个啊,再给点意提示哈,原谅我脑子笨= =
#5
Orphan2015-05-30 13:27
回复 2楼 林月儿
谢谢哈,我电脑上没有VC++不好调试,等到机房再试试= =。阿里嘎倒
#6
yangfrancis2015-05-30 15:28
回复 4楼 Orphan
为了逻辑上看起来更明白,建议还是让zhui去继承ball吧,r的参数从ball类得到,h参数作为zhui私有的。还有,如果zhui和ball当中计算体积的函数重名,当把ball的volume定性为virtual
#7
Orphan2015-05-30 21:21
回复 6楼 yangfrancis
好的,知道啦,谢谢==嘿嘿
1