趁着中秋放假要多补补知识了,感觉自己对C++了解的不够扎实,,为了更好的工作,只好再来看看。
C和C++规定可以用一个结构体,里面即可有数组,也可以有其他变量。C中成员只能是数据,C++除了数据,还可以是函数。
但是,C++提供了类这个东西,所以不需要包含函数的结构体。
1,结构体:
#include<iostream>
using namespace std;
int main(){
struct Student{
char* name;
int num;
float score;
};
}
在C中,用struct Student student1来定义变量,C++中,可以不必用struct,直接在结构体后面加上student1.如:
struct Student{
char* name;
int num;
float score;
}student1;
指向结构体变量的指针:
#include<iostream>
#include<string>
using namespace std;
int main(){
struct Student{
string name;
int num;
float score;
};
Student stu;
Student *p = &stu;
stu.name = "小王";
stu.num = 1001;
stu.score = 80.5;
cout << stu.name << " " << stu.num << " " << stu.score << endl;
cout << (*p).name << " " << (*p).num << " " << (*p).score << endl;
system("pause");
return 0;
}
输出结果是一样的。(*p)表示p指向的是结构体变量。由于“.”的运算符优于“*”,如果用*p.name,就相当于*(p.name)
开辟新空间:
#include<iostream>
#include<string>
using namespace std;
struct Student{
string name;
int num;
float score;
};
int main(){
Student *p;
p = new Student; //定义指向结构体类型Student的数据的指针变量
p->name = "小王"; //用new运算符开辟一个Student型数据的空间
p->num = 1001;
p->score = 80.5;
cout << p->name << " " << p->num << " " << p->score << endl;
delete p; //撤销该空间
system("pause");
return 0;
}
2,类
C++中的类是C中的结构体升级版,结构体是一种构造数据类型,类也是一种构造数据类型,不仅包含变量,还包括函数,通过类定义出来的变量叫“对象”。通过class关键字定义。
- #include <iostream>
- #include<string>
- int main(){
- //通过class关键字类定义类
- class Student{
- public: //类包含的变量
- string name;
- int age;
- float score;
- public: //类包含的函数
- void say(){
- cout<<name<<" "<<age<<" "<<score<<endl;
- }
- };
- //通过类来定义变量,即创建对象
- class Student stu1; //也可以省略关键字class
- //操作类的成员
- stu1.name = "小明";
- stu1.age = 15;
- stu1.score = 92.5f;
- stu1.say();
- return 0;
- }
class 是C++中的关键字,用来声明一个类。public 也是一个关键字,表示后面的成员都是公有的;所谓公有,就是通过当前类创建的对象都可以访问这些成员。除了 public 还有 private,它表示私有的,也就是对象都不能访问这些成员。
在C++中,通过类名就可以创建对象,即将图纸生产成零件,这个过程叫做类的实例化,因此也称对象是类的一个实例。