2、C++是基于C的一种面向对象扩展,它在C原有结构体(struct)的基础上,扩充了struct的功能(增加了成员函数,以及访问控制,继承等),并增加了class这一新定义。实际上class和struct的唯一区别就是:struct中的默认访问控制权限是public,而class的默认访问控制权限是private。
struct RecTangle{
int widthint height
int pos_xint pos_y
}
给他添加一些成员函数
struct RecTangle{
int widthint height
int pos_xint pos_y
int Right()// get right
int Bottom()// get bottom
int Left()// get left
int Top()// get top
}
为了隐藏结构体内的成员,添加访问控制标识:
struct RecTangle{
private:
int widthint height
int pos_xint pos_y
public:
int Right()// get right
int Bottom()// get bottom
int Left()// get left
int Top()// get top
}
如果用class来代替struct,则需要添加访问控制标识.
比如用class来定义类C结构体
class RecTangle{
public:
int widthint height
int pos_xint pos_y
}
在C++ 语言中class是定义类的关键字,C++中也可以使用struct定义类。\x0d\x0a两者区别是,用class定义的类,如果数据成员或成员函数没有说明则默认为private(私有)的,而用struct定义的,默认为public(公共)的。 \x0d\x0a 示例 #include using namespace stdclass C { public: int getAge() const { return age} void setAge( int n ) { age = n} private: int age}int main() { C cc.setAge( 22 )cout 回答于 2022-11-16欢迎分享,转载请注明来源:内存溢出
评论列表(0条)