目录
1.面向过程和面向对象初步认识
C语言是面向过程的,关注的是过程,分析出求解问题的步骤,通过函数调用逐步解决问题。
C++是基于面向对象的,关注的是对象,将一件事情拆分成不同的对象,靠对象之间的交互完成。
2.类的引入
C++中class与struct都可以用来定义类,class默认访问限定符是私有的,
struct默认访问限定符是共有的,因为C++兼容C语言,所以struct还可以
作为结构体使用
C语言中,结构体中只能定义变量,在C++中,结构体内不仅可以定义变量,也可以定义函数。
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; //结构体里面可以定义:1.成员变量 2.成员函数 struct Student//里面的成员默认是公有的 { void SetStudentInfo(const char* name, const char* gender, int age) { strcpy(_name, name); strcpy(_gender, gender); _age = age; } void PrintStudentInfo() { cout << _name << " " << _gender << " " << _age << endl; } char _name[20]; char _gender[3]; int _age; }; int main() { Student s; s.SetStudentInfo("Peter", "男", 18); return 0; } |
上面结构体的定义,在C++中更喜欢用class来代替
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; //类的定义:1.成员变量 2.成员函数 class Student// |