牛骨文教育服务平台(让学习变的简单)
博文笔记

C++与c的写法不同在哪里?

创建时间:2017-06-04 投稿人: 浏览次数:808

例1,hello.cpp

#include<iostream>
//c++的头文件不同,头文件没有.h的后缀
int main(void){
	std::cout<<”hello C++”<<std::endl:
	//std是命名空间,是标准库的命名空间
	//::是英语限定符,cout限定在std里面找
	//cout,输出对象
	//<<,插入运算符,运算符重载,后面可以放整型,字符串型号,返回的是count对象
}

例2,student.cpp//在c++当做,开始把结构当做一种类了,里面可以包含成员变量,也有成员函数,但是还是有些其他区别的,具体有什么区别,你们自己找吧

#include<iostream>
using namespace std;
int main(void){
	struct Student{
		char name[32];
		int age;
		void show(void){
		cout<<”name:”name<<”age:”age<<endl:
	}
	//结构当中定义函数,这个是c++的写法
	};
	struct Student stu={“john”,22};//c语言的方式
	Student stu2={“tom”,23};//C++的写法,在声明结构类型的变量时不用再使用struct关键字
	stu.show()
	stu2.show();
	return 0;
}

例3,

#include<iostream>
#include<cstdio>
 
using namespace std;
int main(void){
//什么是联合?n跟c占用同一块内存空间,而这个内存空间的大小,是靠字节数最大的成员决定的,n跟char都占用4个字节
	union {
		int n;
		char c[4]
	};//c+的写法,声明联合的时候,可以没有名字,叫做匿名联合
 
	n=0x12345678;//16进制的数,一个数字占用4位,两个数字占用一个字节
	//c++的写法,在声明联合类型的变量时候不用再使用union关键字
	printf(“%x,%x,%x,%x,
”,c[0],c[1],c[2],c[3]);
	return 0;
}

 

结果:

78,56,34,12

 

 

例4,枚举类型的区别

//.c文件

#include<stdio.h>
int main(void){
	enum E{a,b,c,d};//定义一个枚举,里面存放的是0,1,2,3,4
	int n=a;//在c语言里面,枚举类型是一个整型的数据类型
	printf(“n=%d
”,n);
	return 0;
}

 

//结果:n=0

 

//.cpp文件

#include<iostream>
using namespace std:
int main(void){
	enum E{a,b,c,d};
	E n=a;
	//c++的写法,//在c++里面,枚举类型不再是一种整型的数据类型,是一种独立数据结构
	//声明枚举变量的时候,没有enum的关键字
	E n=1://这个写法是禁止的,会报错
	//会出现编译错误,错误:从类型”int”到类型”main()::E”的转换无效
	return 0;
}

例5

//C++的bool类型
#include<iostream>
using namespace std:
int main(void){
	bool b=true;
	cout<<b<<endl;
	b=!b;
	cout<<b<<endl;
	cout<<sizeof(bool)<<endl;
	b=10;
	cout<<b<<endl;//这个结果还是1,前面赋值会进行转换
	return 0;
}

结果:

1

0

1//1个字节

1

 

例6//c++中的运算符转换

&& and

|| or

! not

& bitand

| bitor

~ compl

^ xor

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。