C++第二课——开始学习C++

所有源码及练习题请参考gitee: https://gitee.com/pan-fahui/cpp_primer_plus
或源码请参考github: https://github.com/fa-hui/cpp-primer-plus.git
本章节的所有知识点可根据脑图进行重复学习,查漏补缺。
本章内容包括:

  • 创建C++程序
  • C++程序的一般格式
  • #include编译指令
  • main()函数
  • 使用cout对象进行输出
  • 在C++程序中加入注释
  • 何时以及如何使用endl
  • 声明和使用变量
  • 使用cin对象进行输入
  • 定义和使用简单函数

以上内容仅作为脑图学习,以下学习主要以代码位置

1.一个最简单的C++程序

#include <iostream>
int main(void)
{
	using namespace std;
	
	return 0;
}

对上述代码进行拆分理解:
1.iostream: 可以理解成导入的一个包,其含义是只要代码中包含输入输出操的都需要使用iostream包。

2.main函数是C++代码执行的开始,C++代码中有且只能有一个main函数,否则代码会报错。
3.using namespace std: 可以理解为一种规范。C++实现同一种功能可能会有多种不同的方式,比如输入输出操作,这是为了能统一操作,这是使用了std的命名规范。

2.cout和endl的用法

#include <iostream>
using namespace std;
int main(void)
{
	cout << "come up and c++ me some times." << endl;
	return 0;
}

cout:输出打印字符串用cout
<< : 代表插入运算符,将右侧的字符串插入左侧中。
endl: 控制运算符,会使光标移动到下一行,相当于"\n"

3.cin和=的用法

#include <iostream>
using namespace std;
int main(void)
{
	int carrots;
	cout << "How many carrots do you have ? " << endl;
	cin >> carrots;
	cout << "Here are two more.";
	carrots = carrots + 2;
	cout << " Now you have " << carrots << " carrots." << endl;
	return 0;
}

cin:cout是输出流,cin是输入流
=:是赋值运算符,可将右侧的值输入到左侧的变量中,可数学中的等于号需要区分。

4.类的基本用法

#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
	double area;
	cout << "Enter the floor area, in square feet of your home.";
	cin >> area;
	double side;
	side = sqrt(area);
	cout << "That's the equivalent of a square " << side << " feet to the side. " << endl;
	return 0;
}

代码中的sqrt()就是以一个简单的类使用方式,sqrt的作用是给一个数进行开方操作。但因sqrt()函数在cmath,所以必须在代码的开始提供函数原型

4.1 用户自己定义的类

c++中有很多现成的类可以调用,但有些时候根据需求,我们也需要定义自己的类,可以分为:无返回值的函数和有返回值的函数。
无返回值的函数定义如下:

#include <iostream>
void simon(int n);
using namespace std;
int main(void)
{
	simon(3);
	cout << "Pick an integer: ";
	int count;
	cin >> count;
	simon(count);
	cout << "Done!" << endl;
	return 0;
}
//无返回值
void simon(int n)
{
	cout << "Simon says touch your toes " << n << " times. " << endl; 
}

有返回值的函数定义如下:

#include <iostream>
int  stonetolbs(int sts);
using namespace std;
int main(void)
{
	int stone;
	cout << "Enter the weight in stone: ";
	cin >> stone;
	int pounds = stonetolbs(stone);
	cout << stone << " stone = ";
	cout << pounds << " pounds." << endl;
	return 0;
}
//无返回值
int  stonetolbs(int sts)
{
	return 14*sts;
}

以上几乎涵盖了C++基础的所有代码,验证本章节有无学会可查看本文一开始的脑图进行回忆,并查漏补缺。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值