C++基本语法

发布于:2024-03-29 ⋅ 阅读:(25) ⋅ 点赞:(0)

C++是如何工作的



1、新建Hello World工程

1.1使用Visual Studio新建项目

按照下面的图片,建立Main.cpp文件。
在这里插入图片描述

1.2 HelloWorld

#include <iostream>

int main()
{
	using namespace std;
	cout << "你不能放弃。";
	cout << endl;
	cout << "开始学习C++";
	return 0;
}

在这里插入图片描述
注意:
#之后的为预处理命令
using namespace std; 编译指令
cout是一个输出
在这里插入图片描述

1.2.1 命名空间

上述代码可以写成如下模式:

#include <iostream>
//这里我的第一个C++程序,单行注释
using namespace std;
int main()
{	
	/* 多行注释 */
	cout << "你不能放弃。";
	cout << endl;
	cout << "开始学习C++";
	return 0;
}

什么是命名空间?为什么要写using namespace std;这句话呢?

这是C++新引入的一个机制,主要是为了解决多个模块间命名冲突的问题,就像现实生活中两个人重名一个道理。C++把相同的名字都放到不同的空间里,来防止名字的冲突。

例如标准C++库提供的对象都存放在std这个标准名字空中,比如cin、cout、endl,所以我们会看到在C++程序中都会有using namespace std;这句话了。

用域限定符::来逐个制定

#include <iostream>
//这里我的第一个C++程序,单行注释
int main(){		
	std::cout << "限定符书写" << std::endl;
	return 0;
}

用using和域限定符一起制定用哪些名字

#include <iostream>
//这里我的第一个C++程序,单行注释
using std::cout;
using std::endl;
int main(){		
	cout << "限定符书写" << endl;
	return 0;
}

1.2.2 输出输出

C++中的输入输出流分别用cin和cout来表示,使用之前需要以来标准库iostream,即也要开头加一句#include
提到cout,最常用到的还有endl操纵符,可以直接将它插入到cout里,起输出换行的效果。
cout输出的使用
cout可以连续输入。

本质上,是将字符串"Hello"插入到cout对象里,并以cout对象作为返回值返回,因此你还可以用<<在后面连续输出多个内容
cout连续输出

#include <iostream>
using namespace std;
int main(){		
	cout << "hello " << " world";
	return 0;
}

使用endl换行

#include <iostream>
using namespace std;
int main(){		
	cout << "Hello" << endl << "www.dotcpp.com" << endl;
	return 0;
}

cin输入流的使用
接收一个数据之前,都要先定义一个与之类型一致的变量,用来存放这个数据,然后利用cin搭配>>输入操作符,来接收用户从键盘的输入

#include <iostream>
using namespace std;
int main(){		
	//cout << "Hello" << endl << "www.dotcpp.com" << endl;
	int a;
	cout << "请输入数字:" << endl;
	cin >> a;
	cout << "获取a的输入值:" << a << endl;
	return 0;
}

在这里插入图片描述

同样的,cin也可以连续接收多个变量

#include <iostream>
using namespace std;
int main(){		
	//cout << "Hello" << endl << "www.dotcpp.com" << endl;
	int a;
	int b;
	int c;

	cout << "请输入数字:" << endl;
	cin >> a;
	cout << "获取a的输入值:" << a << endl;

	cout << "请输入b、c数字:" << endl;
	cin >> b >> c;
	cout << "获取b的输入值:" << b<< endl;
	cout << "获取c的输入值:" << c << endl;
	return 0;
}

在这里插入图片描述

1.3 注释

//这里我的第一个C++程序,单行注释
/* 多行注释 */

1.4 函数

1.4.1 使用有返回的函数

sqrt是开平方,返回的数据类型是double类型。

#include <iostream>
using namespace std;
int main(){	
	//sqrt是开平方,返回的数据类型是double
	double x=sqrt(36);
	cout << x;
	return 0;
}

1.4.2 自定义函数

自定义函数的调用,必须声明函数原型。

自定义函数的使用

#include <iostream>
using namespace std;
//声明test函数原型
void test1();
void test2(int x);
int test3(int x);
int test4(int x,int y);
int main(){	
	test1();
	test2(43);
	cout << endl;
	cout << "调用test2函数,返回值是:" << test3(3) << endl;
	cout << "调用test2函数,返回值是:" << test4(3,6);
	return 0;
}

//自定义无参数无返回值
void test1() {
	cout << "无参数无返回值的函数test1" << endl;
}

//自定义有参数的函数,没有返回值
void test2(int x) {
	cout << "x的值是:" << x;
}


//自定义有参数的函数,有返回值
int test3(int x) {
	return x * 30;
}

//自定义有多个参数的函数,有返回值
int test4(int x,int y) {
	return x * y;
}
本文含有隐藏内容,请 开通VIP 后查看