class (C++)
关键字 class
声明类类型或定义类类型的对象。
语法
[template-spec]
class [ms-decl-spec] [tag [: base-list ]]
{
member-list
} [declarators];
[ class ] tag declarators;
参数
template-spec
可选模板规范。 有关详细信息,请参阅模板。
class
class
关键字。
ms-decl-spec
可选存储类规范。 有关详细信息,请参阅 __declspec 关键字。
tag
为类提供的类型名称。 标记将变成类范围内的保留字。 标记是可选项。 如果省略,则定义匿名类。 有关详细信息,请参阅匿名类类型。
base-list
此类将从中派生其成员的类或结构的可选列表。 有关详细信息,请参阅基类。 每个基类或结构名称的前面可具有访问说明符(public、private、protected)和 virtual 关键字。 有关详细信息,请参阅控制对类成员的访问中的成员访问表。
member-list
类成员列表。 有关详细信息,请参阅类成员概述。
declarators
声明符列表,指定类类型的一个或多个实例的名称。 如果类的所有数据成员是 public
,则声明符可以包含初始值设定项列表。 与类相比,这在结构(其数据成员默认为 public
)中更为常见。 有关详细信息,请参阅声明符概述。
备注
有关一般类的详细信息,请参阅以下主题之一:
有关 C++/CLI 和 C++/CX 中托管类和结构的信息,请参阅类和结构
示例
// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.
#include <iostream>
#include <string>
using namespace std;
class dog
{
public:
dog()
{
_legs = 4;
_bark = true;
}
void setDogSize(string dogSize)
{
_dogSize = dogSize;
}
virtual void setEars(string type) // virtual function
{
_earType = type;
}
private:
string _dogSize, _earType;
int _legs;
bool _bark;
};
class breed : public dog
{
public:
breed( string color, string size)
{
_color = color;
setDogSize(size);
}
string getColor()
{
return _color;
}
// virtual function redefined
void setEars(string length, string type)
{
_earLength = length;
_earType = type;
}
protected:
string _color, _earLength, _earType;
};
int main()
{
dog mongrel;
breed labrador("yellow", "large");
mongrel.setEars("pointy");
labrador.setEars("long", "floppy");
cout << "Cody is a " << labrador.getColor() << " labrador" << endl;
}
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈