赞
踩
将日常生活中习惯的思维方式引入程序设计中,将需求中的概念直观的映射到解决方案中。
以模块为中心构建可复用的软件系统,提高软件产品的可维护性和可扩展性
C++是一门面向对象的编程语言,理解 C++,首先要理解**类(Class)和对象(Object)**这两个概念
类:指的是一类事物,是一个抽象的概念。类是一种模型,这种模型可以创建出不同的对象实体。
对象实体是类模型的一个具体实例,对象:指的是属于某个类的具体实体。
C++ 中的类(Class)可以看做C语言中结构体(Struct)的升级。结构体是一种构造类型,可以包含若干成员变量,每个成员变量的类型可以不同,可以通过结构体来定义结构体变量,每个变量拥有相同的性质。
代码示例
#include <stdio.h> //定义结构体 Student struct Student{ //结构体包含的成员变量 char *name; int age; int score; }; // 声明函数 void show(struct Student *); int main(){ struct Student stu; //为成员变量赋值 stu.name = "curry"; stu.age = 10; stu.score = 98; //调用函数 show(&stu); return 0; } //结构体的成员变量 void show(struct Student *pst){ printf("%s的年龄是 %d\n,成绩是 %d\n", pst->name, pst->age, pst->score); }
代码运行结果
curry的年龄是10,成绩是98
C++ 中的类也是一种构造类型,但是进行了一些扩展,类的成员不但可以是变量,还可以是函数。通过类定义出来的变量叫做“对象”。
代码示例
#include <iostream> /** * 类和对象 */ using namespace std; //通过class关键字定义学生类 class Student{ public: // 定义变量 char *name; int age; float score; // 声明函数 void say(){ // 输出结果 cout << name << "的年龄是:" << age <<", 成绩是:" << score << endl; } }; int main() { //创建对象 Student stu; //为类的成员变量赋值 stu.name = "curry"; stu.age = 10; stu.score = 92.5f; //调用函数 stu.say(); return 0; }
访问属性 | 属性 | 对象内部 | 对象外部 |
---|---|---|---|
public | 公有 | 可访问 | 可访问 |
protected | 保护 | 可访问 | 不可访问 |
private | 私有 | 可访问 | 不可访问 |
代码示例
#include <iostream> /** * 类的封装 */ using namespace std; // 创建类Person class Person{ public: // 公共权限 string name; // 姓名 protected: // 保护权限 string car; private: // 私有权限 int password; public: void function(){ /** * 所有权限类内都可以访问 */ name = "curry"; car = "小学生跑车"; password = 123446; } }; // 声明函数 void test(){ // 创建对象 Person p; p.name = 'kobe'; // p.car = "法拉第"; 保护权限,在类外不可以访问 // p.password = 134566; 私有权限,在类外不可以访问 } int main() { cout << "Hello, World!" << endl; // 调用函数 test(); return 0; }
使用成员函数可使得我们对变量的控制处理更加精细。
代码示例
#include <iostream> /** * 将成员属性设置成私有属性 */ using namespace std; // 创建Person类 class Person{ public: // 设置姓名 void setName(string name){ myName = name; } // 获取姓名 string getName(){ return myName; } // 设置年龄 void setAge(int age){ // 检测年龄 if(age < 0 || age > 30){ cout << "不好意思,你不是学生了" << endl; return; } myAge = age; } // 获取年龄 int getAge() { return myAge; } private: string myName; // 姓名 int myAge = 18; }; // 声明函数 void test(){ // 创建对象 Person p1; // 对于姓名,可以设置也可以获取 p1.setName("curry"); cout << "p1的姓名是:" << p1.getName() << endl; // 年龄的是只读状态,不可以设置 p1.setAge(55); cout << "p1的年龄为:" << p1.getAge() <<endl; } int main() { // 调用函数 test(); return 0; }
程序运行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。