C++类和对象,结构体

    趁着中秋放假要多补补知识了,感觉自己对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关键字定义。

  1. #include <iostream>
  2. #include<string>
  3. int main(){
  4. //通过class关键字类定义类
  5. class Student{
  6. public: //类包含的变量
  7. string name;
  8. int age;
  9. float score;
  10. public: //类包含的函数
  11. void say(){
  12. cout<<name<<" "<<age<<"  "<<score<<endl;
  13. }
  14. };
  15. //通过类来定义变量,即创建对象
  16. class Student stu1; //也可以省略关键字class
  17. //操作类的成员
  18. stu1.name = "小明";
  19. stu1.age = 15;
  20. stu1.score = 92.5f;
  21. stu1.say();
  22. return 0;
  23. }

class 是C++中的关键字,用来声明一个类。public 也是一个关键字,表示后面的成员都是公有的;所谓公有,就是通过当前类创建的对象都可以访问这些成员。除了 public 还有 private,它表示私有的,也就是对象都不能访问这些成员。

在C++中,通过类名就可以创建对象,即将图纸生产成零件,这个过程叫做类的实例化,因此也称对象是类的一个实例

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值