类的基本概念
类的定义
1 2 3
| class className{ 类成员变量或方法 };
|
类方法可以直接调用类成员变量或方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #include<iostream>
using namespace std;
class Animal { public: char name[64]; char color[64];
void run() { cout << name << "跑起来了" << endl; }
void write() { cout << name << "写字了" << endl; }
void print() { cout << name << endl; cout << color << endl; }
private: int id; };
int main(int argc, char* argv[]) { Animal dog, cat; strcpy(dog.color, "yellow"); strcpy(dog.name, "xiaoming");
strcpy(cat.name, "xiaohua"); strcpy(cat.color, "black");
dog.print(); cat.print();
dog.run(); dog.write();
cat.run(); cat.write();
return 0; }
|
public 公有的,类的外部可以直接调用
private私有的,类的外部不可以直接调用,可以通过方法get或set
protected保护的,在类的外部调用不到,子类可以调用