/*写一个程序,输出张三、李四两个人的姓名、年龄*/
/*利用变量存储*/
person1.c
#include <stdio.h>
int main(void)
{
char *zs_name = "zhangsan";
int zs_age = 18;
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;
}
/*利用数组存储*/
person2.c
#include <stdio.h>
int main(void)
{
char *names[] = {"zhangsan", "lisi"};
int ages[] = {10, 16};
/*如果还有职业还要加数组吗?*/
char *work[] = {"teacher", "doctor"};
int i;
for(i=0; i<2; i++)
{
printf("name = %s\n, age = %d\n", names[i], ages[i]);
}
return 0;
}
/*利用结构体存储*/
person3.c
#include <stdio.h>
struct person
{
char *name;
int age;
char *work;
};
int main(void)
{
struct person persons[] =
{{"zhangsan", 20, "teacher"},
{"lisi", 16, "doctor}};
int i;
for(i=0; i<2; i++)
{
printf("name = %s\n, age = %d\n", persons[i].name, persons[i].age, persons[i].work);
}
return 0;
}
/*结构体中内嵌函数指针,属性加方法*/
person4.c
#include <stdio.h>
struct person
{
char *name;
int age;
char *work;
void (*printinfo)(struct person *per);
};
void printInfo(struct person *per)
{
printf("name = %s\n age = %d\n work = %s\n", per->name, per->age, per->work);
}
int main(void)
{
struct person persons[] =
{{"zhangsan", 20, "teacher", printInfo},
{"lisi", 16, "doctor", printInfo}};
persons[0].printinfo(&persons[0]);
persons[1].printinfo(&persons[1]);
return 0;
}
/*用c++的方法,引入类,在类中直接写函数*/
#include <stdio.h>
class person
{
public:
char *name;
int age;
char *work;
void printInfo(void)
{
printf("name = %s\n age = %d\n work = %s\n", name, age, work);
}
};
int main(void)
{
struct person persons[] =
{{"zhangsan", 20, "teacher"},
{"lisi", 16, "doctor"}};
persons[0].printinfo();
persons[1].printinfo();
return 0;
}
总结:面向对象的三大思想:封装、继承、多态。
可以在类中直接写函数,但是在类中的函数和属性都要加权限private或者public
要打印一个人的信息,首先要把这个人想象成一个对象,这个对象有很多属性。然后打印就是操作这个对象的属性。