第二章 开始学习C++

本章内容

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

2.1 进入C++

myfirst.cpp  --  display a message
————————————————————————————————————————————————————————————————————————————————————————
#include<iostream>			//预处理编译指令:在源代码被编译之前,替换或者添加文本

using namespace std;		//编译指令:using namespace,使定义可见

int main()					//函数头。C++运行时,通常从main()函数开始;int为函数返回类型
{
    
    
	cout << "Come up and C++ me some time.";		//message
	cout << endl;			//endl:重启一行 = cout<<"\n"; \n为换行符
	cout << "You won't regret it!" << endl;
	return 0;				//返回语句,只适用于main()。若不写,main()在函数末尾自动添加
}
—————————————————————————————————————————————————————————————————————————————————————————

规则如下

  • 注释以前缀 “//” 标识
  • C++对大小写敏感
  • int main() = void main() = int main(void)
  • iostream称为头文件,老式C头文件(如math.h)转换为cmath
  • 名称空间编译指令:using namespace。使用cout的三种方法:std::cout、using std::out;、using namespace std;
  • 使用cout输出:cout对象 + 插入运算符 + 字符串/变量 ——> cout<<“C++ RULES”;
  • C++中,“ ; ” 标示了语句的结尾
  • 一行代码中不可分割元素叫作标记,如int、main

2.2 C++语句

									程序清单2.2 carrots.cpp
————————————————————————————————————————————————————————————————————————————————————————
#include<iostream>			

using namespace std;	

int main()			
{
    
    
	int carrots;		//声明变量
	carrots = 25;		//初始化变量
	cout << "I have ";		
	cout << carrots;
	cout << " carrots.";
	cout << endl;		
	carrots = carrots - 1;	//修改变量
	cout << "Now, I have " << carrots << " carrots." << endl;
	return 0;				
}
————————————————————————————————————————————————————————————————————————————————————————

规则如下

  • 声明语句:int carrots; 指明需要的内存以及该内存单元的名称
  • C++中,使用变量必须先声明它
  • 赋值语句:carrots = 25; “ = ”称为 赋值运算符

2.3 其他C++语句

  1. cin语句:cin >> 字符串/变量
  2. cout拼接:cout << string1 << string2 << … (<< endl);
  3. 类简介:类是用户定义的一种数据形式,类定义描述数据格式及其用法,对象是类中的实体,如演员和胡歌的关系。

2.4 函数

	C++函数分两种:有返回值和没有返回值。除了库函数,用户也可以自己创建函数。

有返回值的函数

	有返回值的函数将生成一个值,而这个值可赋给变量或者在其他表达式中使用。如x = sqrt(6.25);
  • sqrt() 称为调用函数;
  • 6.25称为参数;
  • 2.5称为返回值,返回给调用函数sqrt();

在程序中使用 sqrt() 时,必须提供函数原型。两种实现方案:

  • 在源代码中输入函数原型;
  • 包含头文件 cmath ,其中定义了原型。
    sqrt() 原型: double sqrt(double);

函数变体

  • 有些函数需要多个参数,参数用逗号隔开;
  • 有些函数不接受任何参数;
  • 还有一些函数没有返回值。
    注意:C++中,函数调用必须包括括号,即使没有参数

用户定义函数

	 用户可以按照规则任意定义函数,定义内容包括函数头、函数体、参数、返回值、原型

函数格式:

type functionname(argumentlist)
{
    
    
	statements
}

**********示 例

						程序清单2.6 convert.cpp
——————————————————————————————————————————————————————————————————————————————————————————
#include<iostream>

using namespaces std;

int stonetolb(int);
int main()
{
    
    
	int stone;
	cout<< "Enter the weight in stone: ";
	cin>> stone;
	int pounds = stonetolb(stone);
	cout<< pounds << "pounds." << endl;
	return 0;
}

int stonetolb(int sts)
{
    
    
	return 14 * sts;
}
——————————————————————————————————————————————————————————————————————————————————————————

猜你喜欢

转载自blog.csdn.net/sayonara_w/article/details/115208224
今日推荐