类与对象
/* 类与对象: 1.类是一种用户自定义的数据类型(函数,数据) 2.类是具有相同的属性和行为的对象的集合 3.类是对象的抽象,对象是类的具体 4.对象:通过使用类类型定义的变量 */
定义类
/* 如何定义类?语法: class 类名 { 默认是私有的 // 成员:1.数据 2.函数 //访问权限修饰关键字 public: // 公有的 // 成员:1.数据 2.函数 private: // 私有的(只允许当前类使用) // 成员:1.数据 2.函数 protected: // 被保护的(只允许当前类或子类使用) // 成员:1.数据 2.函数 } */
定义对象
/* 如何定义对象,语法: 类名 对象名; e.g. Sheep xiYangYang */
访问成员
#include <iostream> using namespace std; class Sheep { public: char name[32]; private: int age; public: void eat() { cout << "让我们吃点草吧,咩!" << endl; } void speak(); // 函数声明 void setAge(int num) { age = num; } }; void Sheep::speak() // 在类的外面实现 { cout << "我的年龄是" << age << "岁" << endl; } int main() { Sheep xiYY; // xiYY.name = "喜羊羊"; 这个是错误写法 strcpy(xiYY.name, "喜羊羊"); // xiYY.age = 8; 错误写法,私有属性无法直接访问!! xiYY.setAge(8); // 通过使用函数接口 xiYY.eat(); xiYY.speak(); cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl; // 通过指针实现: Sheep* p; p = &xiYY; p->eat(); p->speak(); return 0; } /* 了解:class 和 struct 1.在 C语言里面,有 struct 没有 class 2.在 C语言里面,struct 里面“不能有”函数 3.在 C++ 里面,struct 里面“可以有”函数 4.在 C++ 里面,我们可以用 struct 定义结构体,也可以用它定义类 5.在 C++ 里面,用 class 定义的类,它的成员默认访问权限是私有的 而用 struct 定义类,它的成员默认访问权限是公有的,所以不太符合封装的思想 */
String 类
/* String 是 C++ 中的字符串 类似于C语言中的字符串数组 里面包括许多方法,使用时需要额外包含<string> */
#include <iostream> #include <string> // 先预处理,下面才能使用 string using namespace std; int main() { char ch; string str; str = "abc123"; ch = str[2]; // 字母 c ch = str.at(1); // 字母 b str.length(); str.clear(); str.empty(); str == str; return 0; }
浙公网安备 33010602011771号