前言:C语言过度到C++
下面从打印人的姓名和年龄为切入点
1、初学C语言时候的写法
注意:当需要打印很多人的信息的时候,需要列举非常多
#include
int main(int argc, char **argv)
{
char *zs_name = "zhangsan";
int zs_age = 10;
char *ls_name = "lisi";
int ls_age = 16;
printf("name = %s, age = %d\n", zs_name, zs_age);
printf("name = %s, age = %d\n", ls_name, ls_age);
return 0;
}
2、使用数组存储多个人的信息
注意:属性越多增加的数组就越多,比如加入工作
#include
int main(int argc, char **argv)
{
char *names[] = {"zhangsan", "lisi"};
char ages[] = {10, 16};
char *work[] = {"teacher", "doctor"};
int i;
for (i = 0; i < 2; i++)
{
printf("name = %s, age = %d\n", names[i], ages[i]);
}
return 0;
}
3、引入C语言的结构体
注意:对于打印每个人的信息,引用的时候还是比较别扭的(persons[0].printInfo(&persons[0]);)有点让人不太好理解,后面向C++过度
#include
struct person {
char *name;
int age;
char *work;
void (*printInfo)(struct person *per);
};
void printInfo(struct person *per)
{
printf("name = %s, age = %d, work = %s\n", per->name, per->age, per->work);
}
int main(int argc, char **argv)
{
struct person persons[] = {
{"zhangsan", 10, "teacher", printInfo},
{"lisi", 16, "doctor", printInfo},
};
persons[0].printInfo(&persons[0]);
persons[1].printInfo(&persons[1]);
return 0;
}
4、C++是在C的基础上变形而来的(对结构体扩展),类的核心就是结构体
注意这里是person5.cpp文件,这样编译或许有很多警告,但是可以编译通过的
#include
struct person {
char *name;
int age;
char *work;
void printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
};
int main(int argc, char **argv)
{
struct person persons[] = {
{"zhangsan", 10, "teacher"},
{"lisi", 16, "doctor"},
};
persons[0].printInfo();
persons[1].printInfo();
return 0;
}
5、正式转到C++
注意:把struct换成class,并给内部参数添加属性(public)
#include
class person {
public:
char *name;
int age;
char *work;
void printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
};
int main(int argc, char **argv)
{
struct person persons[] = {
{"zhangsan", 10, "teacher"},
{"lisi", 16, "doctor"},
};
persons[0].printInfo();
persons[1].printInfo();
return 0;
}