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,那么就会编译报错。
*/