C++第一篇--类的引入
1. 用C语言输出两个人的信息
Person1.c:通过字符实现
#include <stdio.h>
int main(int argc,int **argv)
{
char *zs_name = "zhangsan";
int zs_age = 10;
char *ls_name = "lisi";
int ls_age = 16;
printf("name=%s,age=%d
",zs_name,zs_age);
printf("name=%s,age=%d
",ls_name,ls_age);
}
Person2.c:通过数组实现
#include <stdio.h>
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
", names[i], ages[i]);
}
return 0;
}
Person3-1.c:通过结构体实现
#include <stdio.h>
struct person{
char *name;
char age;
char *work;
};
int main(int argc,int **arcv)
{
struct person Person[] = {
{"zhangsan",18,"Teacher"},
{"lisi",29,"Doctor"},
};
int i;
for(i = 0;i<2;i++)
{
printf("name is %s,age is %d,work is %s
",Person[i].name,Person[i].age,Person[i].work);
}
return 0;
}
Person3-2.c:通过结构体实现,并在结构体实现打印函数
#include <stdio.h>
struct person{
char *name;
char age;
char *work;
void (*printInfo)(struct person *per); //C中结构体只可以实现函数指针
};
void printInfo(struct person *per)
{
printf("name is %s,age is %d,work is %s
",per->name,per->age,per->work);
}
int main(int argc,int **arcv)
{
struct person Person[] = {
{"zhangsan",18,"Teacher",printInfo},
{"lisi",29,"Doctor",printInfo},
};
Person[0].printInfo(&Person[0]);
Person[1].printInfo(&Person[1]);
return 0;
}
2. 引入C++类
-
为了程序的简洁,现在用C++类实现,十分直观简单
-
C++对结构体进行的扩展,不仅可以直接实现函数,还可以直接访问结构体的属性,故引入C++类
Person4.cpp
#include <stdio.h>
class person{
public:
char *name;
char age;
char *work;
void printInfo(void)
{
printf("name is %s,age is %d,work is %s
",name,age,work);
}
};
int main(int argc,int **arcv)
{
struct person Person[] = {
{"zhangsan",18,"Teacher"},
{"lisi",29,"Doctor"},
};
Person[0].printInfo();
Person[1].printInfo();
return 0;
}
3. 展望
-
接下来会开始写关于面向对象编程
-
以上所有代码直接在Ubuntu下编译执行即可,之后代码也是如此
//C语言编译执行命令
gcc Person.c -o Person
./Person
//C++语言编译执行命令
g++ Person.c -o Person
./Person