类的特点:
- 类(class)可以包含很多可以被调用的函数(functions)
- 类中除非用public修饰,否则它的成员变量和成员方法对外是不可见的
- 类中有一对特殊的函数,构造函数(constructor)和析构函数(destructor),它们在对象被创建和销毁时会自动调用。而结构体中没有。
- 类可以使用特殊方法(成员方法)定义处理新数据类型的操作符
- 类可以被用作定义其它类的基类(继承)
- 声明一个新类型的变量(一个类的实例,即一个对象)只需要类名即可,并不需要class关键字
在c++中,结构体和类之间的唯一区别是成员变量和成员方法默认的可访问性。在结构体中,它们是public的; 在class中它们是private的。
英文原版:
How does a C++ class differ from a C struct? There are a few differences. The key ones are:
- A class can also contain functions [called methods].
- The member variables and methods are hidden from the outside world, unless their declaration follows a public label.
- There can be a pair of special methods – the constructor and destructor – that are run automatically when an instance of the class [an object] is created and destroyed.
- Operators to work on the new data type can be defined using special methods [member functions].
- One class can be used as the basis for the definition of another [inheritance].
- Declaring a variable of the new type [an instance of the class; an object] requires just the name of the class – the keyword class is not required.
But what about a struct in C++? The last example here gives a clue. The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.