BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #47825同步于 2010/12/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

这个程序我想问……

heshanshan
2010/12/15镜像同步9 回复
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; class shape { public: void getArea() { cout<<"The area of this shape is:"<<area<<endl; } protected: float area; }; class Rectangle:public shape { public: void input_Rc(); void getArea_Rc() { area=length*wide; } protected: float length,wide; }; void Rectangle::input_Rc() { cout<<"please input the length and the wide of this rectangle:"<<endl; cin>>length>>wide; cout<<"The length is:"<<length<<" "<<"The wide is:"<<wide<<endl; } class Circle:public shape { public: void getArea_Ci(); private: float radius; }; void Circle::getArea_Ci() { cout<<"please input the radius of this circle:"<<endl; cin>>radius; cout<<"The radius is:"<<radius<<endl; area=3.1415926*radius*radius; } class Square:public Rectangle { public: void input_Sq(); private: float side; }; void Square::input_Sq() { cout<<"please input the side:"<<endl; cin>>side; length=side; wide=side; } main() { Rectangle re; re.input_Rc(); re.getArea_Rc(); re.getArea(); cout<<endl; Circle ci; ci.getArea_Ci(); ci.getArea(); cout<<endl; Square sq; sq.input_Sq(); sq.getArea_Rc(); sq.getArea(); system("pause"); return 0; } 我知道在shape和Rectangle里不能定义为private的形式,派生类中不能访问基类中的private,但是写成protected形式的就可以,可是如果我在shape和Rectangle里就想用private,应该怎么写呢? 初学c++,谢谢大家了:)
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
guozi机器人#1 · 2010/12/15
问题是写了private就是不能用啊。。。 protected就是表示子类可以访问 所以你的要求基本是不可能的 如果非独辟蹊径能用。。 那就用反射,通过一定的bindingflag能射出来 【 在 heshanshan (shanshan2512) 的大作中提到: 】 : #include<iostream> : #include<stdio.h> : #include<stdlib.h> : ...................
heshanshan机器人#2 · 2010/12/15
反射和bindingflag是什么啊?我们还没有学过……也就是说如果要求用private的话,我的这个思路是错的啊…… 【 在 guozi 的大作中提到: 】 : 问题是写了private就是不能用啊。。。 : protected就是表示子类可以访问 : 所以你的要求基本是不可能的 : ...................
guozi机器人#3 · 2010/12/15
你可以好好看看面向对象相关的书籍 private是干嘛用的 反射是.NET的东西 你如果用的不是VS里面的CPP,基本上没啥瓜葛了 【 在 heshanshan (shanshan2512) 的大作中提到: 】 : 反射和bindingflag是什么啊?我们还没有学过……也就是说如果要求用private的话,我的这个思路是错的啊……
a206206机器人#4 · 2010/12/15
书上有详细的class属性介绍,可以好好看看。。 ps:ls的学长,什么时候当上斑竹了。。。
heshanshan机器人#5 · 2010/12/15
ls的学长,什么时候当上斑竹了。。。 ??? 【 在 a206206 的大作中提到: 】 : 书上有详细的class属性介绍,可以好好看看。。 : ps:ls的学长,什么时候当上斑竹了。。。 : -- : ...................
wo机器人#6 · 2010/12/15
为了体现良好的封装性,可以把要访问的变量设为private,然后定义public的方法来间接访问它,比如下面 class shape { private: float area; public: float GetArea(){return area;} void SetArea(float value){ area = value;} }; 这样,虽然shape的派生类无法直接访问area,却可以通过两个公共方法来间接读和写area的值。这就是面向对象的思想~
rebirthatsix机器人#7 · 2010/12/16
getter and setter
guozi机器人#8 · 2010/12/16
re ls和lss 原来。。lz是这个意思 【 在 rebirthatsix (茫犭者-算法盲) 的大作中提到: 】 : getter and setter
zhuifengliuq机器人#9 · 2010/12/17
6楼观点正解,给private变量定义public接口。