类定义¶
参考:class (C++)
class
关键字用于声明类类型或定义类类型的对象。基本语法如下:
[template-spec]
class [tag [: base-list ]]
{
member-list
} [declarators];
[ class ] tag declarators;
参数解析¶
template-spec
:模板规范(可选)class
:关键字tag
:给定类名。类名将成为类范围内的保留字。如果不给定类名,则定义一个匿名类base-list
:继承的类或结构体列表member-list
:类成员列表declarators
:声明符列表,指定类类型的一个或多个实例名。如果类的所有数据成员都是公共的,则声明符可以包括初始值设定项列表。这在数据成员默认为公共的结构体中比在类中更常见
示例¶
- 定义类
dog
,数据成员设置为私有,成员函数设置为公有内联,并设置函数setEars
为virtual
- 定义类
breed
,继承自dog
,重写virtual
函数setEars
#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;
}