C语言中的class的应用

Python016

C语言中的class的应用,第1张

1、C语言里没有class函数的概念,class是C++中的关键字。

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

}

Class可以通过extend关键字实现继承。super关键字表示父类的构造函数,用来新建父类的this对象。

子类须在constructor方法中调用super方法,这样才能得到父类的this,否则会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。

调用函数使用的例子

class A {

constructor() {

console.log(new.target.name)

}

}

class B extends A {

constructor() {

super()

}

}

new A() // A

new B() // B

扩展资料

实例属性的新写法

class IncreasingCounter {

constructor()

{

this._count = 0

}

_count = 0//_count定义在类的最顶层与上面的constructor()写法等价

get value() {

console.log('Getting the current value!')

return this._count

}

increment()

{

this._count++

}

}

在C++ 语言中class是定义类的关键字,C++中也可以使用struct定义类。

两者区别是,用class定义的类,如果数据成员或成员函数没有说明则默认为private(私有)的,而用struct定义的,默认为public(公共)的。  

 示例 #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 <<"My age: " <<c.getAge() <<endlreturn 0

}

作为面向对象程序设计的基础,掌握class的基本结构和特性是十分重要的。