struct和class

1.在C中和C++中的区别
这里写图片描述

2.代码
使用 struct 来定义类的一个反面例子:

#include <iostream>
using namespace std;
struct Student
{
    Student(char *name, int age, float score);
    void show();
    char *m_name;
    int m_age;
    float m_score;
};
Student::Student(char *name, int age, float score)
  : m_name(name), m_age(age), m_score(score){ }

void Student::show()
{
    cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
int main()
{
    Student stu("小明", 15, 92.5f);
    stu.show();
    Student *pstu = new Student("李华",16,96);
    pstu -> show();
    return 0;
}
/*
运行结果:
小明的年龄是15,成绩是92.5
李华的年龄是16,成绩是96

这段代码可以通过编译,说明struct默认的成员都是public属性的,否则不能通过对象访问成员函数。
如果将struct关键字替换为class,那么就会编译报错。
*/ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值