第2章开始学C++
2.2 C++语句
//carrots.cpp
#include<iostream>
int main()
{
using namespace std;//名称空间
int carrots;//声明变量 声明了一个整数型的变量 carrots
cout << "How many carrots do you have" << endl;
cin >> carrots;//cin 是一个智能对象,它可以将通过键盘输入的一系列字符转换为接收信息的变量能够接收的形式
cout << "Here are two more." << endl;
carrots = carrots + 2;//赋值运算
cout << "Now you have " << carrots << " carrots" << endl;
return 0;
}
2.3类的简介
类是C++中面向对象编程(oop)的核心概念之一
- 类定义描述的是数据格式及其用法,而对象则是根据数据格式规范创建的实体;类描述了一种数据类型的全部属性(包括可使用它执行的操作),对象是则是根据数据格式规范创建的实体。
- 类描述指定了可对类对象执行的所有操作。
2.4函数
C++函数分两种:有返回值的和没有返回值的
2.4.1使用 有返回值的函数
有返回值的函数将生成一个值,而这个值可赋给变量或者在其他地方表达式中使用。sqrt()函数,它返回平方根。
x = sqrt(6.25);//returns the value 2.5 and assigns it to x
函数原型:函数原型之于函数就像变量声明之于变量——指出涉及类型。sqrt()的函数原型如下:
double sqrt(double);//function prototype
第一个double意味着sqrt()将返回一个double值。括号中的double意味着sqrt()需要一个double的参数。因此该原型对sqrt()的描述和下面代码中使用的函数相同;
double x ;//declare x as a type double variable
x=sqrt(6.25);
在程序使用sqrt()时,也必须提供原型,有两种方法:
1.在源代码中写出函数原型;
2.包含头文件cmath,其中定义了原型(常采用这种方式)
//sqrt.cpp
#include<iostream>
#include<cmath>
int main()
{
using namespace std;
double area;
cout << "Enter the floor area,in square feet,of your home:";
cin >> area;
double side;
side = sqrt(area);//or double side = sqrt (area);
cout << "That's the equivalent of a square " << side << " feet to the side." << endl;
cout << "How fascinating!" << endl;
return 0;
}
2.4.2 使用不返回值的函数
可以在函数原型中使用关键字void来指定返回类型,以指出函数没有返回值;
void bucks(double);//prototype for function with no return value
2.4.3 用户定义函数
每个C++程序都必须有一个main()函数,用户必须对它进行定义。假设需要添加另一个用户定义的函数,**通常要把原型放到main()定义之前。**对于库函数,在使用之前必须提供其原型,通常把原型放到main定义之前,如头文件 #include。对于提供新函数的源代码最简单的方法是将代码放在main的后面。
//ourfunc.cpp
#include<iostream>
void simon(int);//function prototype for simon(函数simon的原型)
int main()
{
using namespace std;
simon(3); //call the simon() function
cout<< "pick an integer:";
int count
cin>> count;
simon(count); //call it again
cout<< "Done!"<<endl;
return 0;
}
void simon(int n)//define the simon()function
{
using namespace std;
cout<<"Simon says touch your toes "<<n<<"time."<<endl;
}//void function don't need return statements
如果simon的类型不是void,即存在返回值,那么我们可以在main函数中声明一个参数,如 int simple;
simple = simon (3);
用户定义的有返回值的函数
//convert.cpp
#include <iostream>
int stonetolb (int);
int main()
{
using namespace std;
int stone ;
cout<<"Enter the weight in stone:";
cin>>stone;
int pounds=stonetolb(stone);
cout<<stone<<"stone=";
cout<<pounds<<"pounds."<<endl;
return 0;
}
int stoneable(int sts)
{
return 14*sts
}