红联Linux门户
Linux帮助

Linux C/C++区别:类型声明、struct

发布时间:2017-02-16 10:33:49来源:linux网站作者:新生代黑马
C有数组、结构体、指针、函数、宏
C++有命名空间、引用、默认参数、模板、函数重载、自定义操作符、内联、构造/析构、私有/保护成员、友元、异常。
 
一、数据类型的声明
1.C++允许数据声明出现在程序的任意位置
C代码(异常)
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
for(int i=0; i<5; i++)
printf("hello %d\n", i);
return 0;
}
C++代码(正常)
#include <iostream>
#include <cstdio>
using namespace std;
int main(int argc, char* argv[])
{
for(int i=0; i<5; i++)
printf("hello %d\n", i);
return 0;
}
2.c++允许使用结构体名定义实体
C代码(异常)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//C语言中不能直接使用结构体名定义实体
struct Person
{
char name[20];
int age;
};
int main(int argc, char* argv[])
{
//struct Person person;
Person person;
strcpy(person.name, "Tom");
person.age = 5;
printf("%s age is %d\n", person.name, person.age);
return 0;
}
C++代码(正常)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
//C++中可以直接使用结构体名定义实体
struct Person
char name[20];
int age;
};
int main(int argc, char* argv[])
//
Person person;
strcpy(person.name, "Tom");
person.age = 5;
printf("%s age is %d\n", person.name, person.age);
return 0;
}
 
二、struct
1.C++允许对struct内数据成员进行操作的函数,作为struct成员声明。
C代码(异常)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//C中不允许对struct内数据成员进行操作的函数,作为struct成员声明
struct Person
{
char name[20];
int age;
//
void output() { printf("%s age is %d\n", name, age); }
};
int main(int argc, char* argv[])
{
struct Person person;
strcpy(person.name, "Tom");
person.age = 5;
person.output();
return 0;
}
C++代码(正常)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
//C++中允许对struct内数据成员进行操作的函数,作为struct成员声明
struct Person
{
char name[20];
int age;
//
void output() { printf("%s age is %d\n", name, age); }
};
int main(int argc, char* argv[])
{
//
Person person;
strcpy(person.name, "Tom");
person.age = 5;
person.output();
return 0;
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/28455.html