C++ Primer5 第二章笔记整理(基本语句)
1 2.1 myfirst.cpp 2 #include <iostream> //预处理编译器指令 3 int main() //函数头(返回类型)+形参列表 ()不接受任何信息 4 { //函数体 5 using namespace std; //名称空间 std::cout 6 cout << "Come up and C++ me some time."; //""字符串 7 cout << endl; 8 cout << "You won't regret it!" << endl; 9 return 0; //结束函数 10 }
1 2.2 carrot.cpp 2 #include <iostream> 3 int main() 4 { 5 using namespace std; 6 int carrots; //声明语句 7 carrots = 25; 8 cout << "I have " << carrots << " carrots." << endl; 9 carrots = carrots - 1; 10 cout << "Crunch, crunch. Now I have " << carrots << " carrots." << endl; 11 return 0; 12 }
2.3 其他C++语句
1 2.3 getinfo.cpp 2 #include <iostream> 3 int main() 4 { 5 using namespace std; 6 int carrots; 7 cout << "How many carrots do you have?" << endl; 8 cin >> carrots; 9 cout << "Here are two more. "; 10 carrots = carrots + 2; 11 cout << "Now you have " << carrots << " carrots." << endl; 12 return 0; 13 }
类
类描述了一种数据类型的全部属性,对象是根据这些描述创建的实体。
2.4 函数
double sqrt(double);
1 2.4 sqrt.cpp 2 #include <iostream> 3 #include <cmath> 4 { 5 using namespace std; 6 double area; 7 cout << "Enter the floor area, in square feet, of your home:"; 8 cin >> area; 9 double side; 10 side = sqrt(area); 11 cout << "That is the equivalent of a square " << side << " feet to the side." << endl; 12 cout << "How fascinating!" << endl; 13 return 0; 14 }
g++ sqrt.C -lm
double side = sqrt(area);
double pow(double, double); //x^y
int rand(void); //返回随机整数
自己定义的无返回值的函数:
1 2.5 ourfunc.cpp 2 #include <iostream> 3 void simon(int); //函数原型 没有返回值,输入一个int参数 4 int main() 5 { 6 using namespace std; 7 simon(3); 8 cout << "Pick an integer:"; 9 int count; 10 cin >> count; 11 simon(count); 12 cout << "Done!" << endl; 13 return 0; //返回给操作系统,通常约定退出值为0意味着程序运行成功 14 } 15 void simon(int n) //自己定义函数的源代码在main函数后面 16 { 17 using namespace std; 18 cout << "Simon says touch your toes " << n << " times. " << endl; 19 }
自己定义的有返回值的函数:
1 2.6 convert.cpp 2 #include <iostream> 3 int stoneolb(int); 4 int main() 5 { 6 using namespace std; 7 int stone; 8 cout << "Enter the weight in stone:"; 9 cin >> stone; 10 int pounds = stoneolb(stone); 11 cout << stone << "stone =" << pounds << "pounds." << endl; 12 return 0; 13 } 14 int stoneolb(int sts) 15 { 16 return 14*sts; 17 }

浙公网安备 33010602011771号