类名
类声明将名为类名称或类类型的新类型引入程序中。 除前向声明外,这些类声明还用作给定翻译单元的类的定义。 每个翻译单元可能只有一个给定类类型的定义。 通过使用这些新的类类型,可以声明对象,并且编译器可以执行类型检查以验证未对这些对象执行与类型不兼容的操作。
备注
该类型检查的示例是:
// class_names.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Point {
public:
unsigned x, y;
};
class Rect {
public:
unsigned x1, y1, x2, y2;
};
// Prototype a function that takes two arguments, one of type
// Point and the other of type pointer to Rect.
int PtInRect( Point, Rect & );
int main() {
Point pt;
Rect rect;
rect = pt; // C2679 Types are incompatible.
pt = rect; // C2679 Types are incompatible.
// Error. Arguments to PtInRect are reversed.
// cout << "Point is " << PtInRect( rect, pt ) ? "" : "not"
// << " in rectangle" << endl;
}
如前面的代码所示,对类类型的对象执行的操作(如赋值和参数传递)受与内置类型的对象相同的类型检查的约束。
由于编译器可以区分类类型,因此可以基于类类型参数以及内置类型参数重载函数。 有关重载函数的详细信息,请参阅函数重载和重载。