1. 访问控制
有三种,分别是public ,protected , private
private只提供内部的函数使用
public类外的程序可以使用
#include <stdio.h> class Person {//类的首字母应该大写 private: char *name; int age; char *work; public: void setName(char *n) { name = n; } int setAge(int a) { if (a < 0 || a > 150) { age = 0; return -1; } age = a; return 0; } void printInfo(void) { printf("name = %s, age = %d, work = %s\n", name, age, work); } }; int main(int argc, char **argv) { Person per;//称per是一个类的对象 //per.name = "zhangsan"; per.setName("zhangsan"); per.setAge(200); per.printInfo(); return 0; }
做一些小的改进,当前对象
class Person { private: char *name; int age; char *work; public: void setName(char *name) { this->name = name; } int setAge(int age) { if (age < 0 || age > 150) { this->age = 0; return -1; } this->age = age; return 0; } void printInfo(void) { printf("name = %s, age = %d, work = %s\n", name, age, work); } }; int main(int argc, char **argv) { Person per; //per.name = "zhangsan"; per.setName("zhangsan"); per.setAge(200); per.printInfo(); return 0; }