易采站长站为您分析C++中声明类的class与声明结构体的struct关键字,默认情况下结构的所有成员均是公有的,而类的所有成员是私有的,需要的朋友可以参考下
class
class 关键字声明类类型或定义类类型的对象。
语法
[template-spec]
class [ms-decl-spec] [tag [: base-list ]]
{
member-list
} [declarators];
[ class ] tag declarators;
参数
template-spec
可选模板说明。
ms-decl-spec
可选存储类说明有关更多信息
tag
给定于类的类型名称。在类范围内的标记成为了保留字。标志是可选项。如果省略,定义匿名类。
base-list
此类派生其成员的类或结构的可选列表。
member-list
类成员列表。
declarators
指定类类型一个或多个实例名称的声明符列表。如果类的所有数据成员是 public,声明符可以包含初始值设定项列表。
使用举例
// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.
#include <iostream>
#include <string>
#define TRUE = 1
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;
}
struct
struct 关键字定义结构类型和/或结构类型的变量。
[template-spec] struct[ms-decl-spec] [tag [: base-list ]]
{
member-list
} [declarators];
[struct] tag declarators;
参数
与class的参数相同,可以参照上面的。










