1.给出一段代码作为讲解载体
#include<iostream>
int main()
{
using namespace std;
cout << "hello c++";
cout << endl;
cout << "insist to study!" << endl;
cin.get();
return 0;
}
程序块 | 意义 |
---|---|
#include | 预处理器编译指令,程序中的iostream为预处理的文件 |
using namespace | 编译指令,指定std |
cout | c++提供的输出工具 |
<< | 重载操作符 |
cin.get() | c++提供的输入工具,程序执行后,需要在控制台中键入任何字符则继续执行 |
若要进行输入输出操作,则c++代码需要提供一下两行代码:
#include<iostream>
using namespace std;
使用cout
和cin
进行输出和输入时,必须包含头文件。
using
为一个编译指令。此处std
为namespace
(名称空间)单元,指定名称空间std
。对于名称空间,在此处作一个简要的介绍。举一个例子:A、B程序员都用c++写了一个函数hello()
,并且都已经封装。现在,C程序员想用他们中某个人写的helllo()
函数,怎么区分呢?c++提供了名称空间特性。为了使C程序员可以调用hello()
函数,A、B程序员各自封装一个名称空间单元Ap、Bp。这样,C程序员想要调用A程序员的hello()
函数则可以使用Ap::hello()
,B同理。这样就能防止冲突了。
利用直接使用名称单元的形式,文章的开始处的代码可以和下面改写后的代码有相同的结果。
#include<iostream>
int main()
{
// using namespace std;
std::cout << "hello c++";
std::cout << std::endl;
std::cout << "insist to study!" << std::endl;
std::cin.get();
return 0;
}
关于cin.get()
的用法,给出一个例子说明。
#include<iostream>
int main()
{
using namespace std;
int carrots;
cout << "how many carrot do you have?" << endl;
cin >> carrots;
cout << "here are two more.";
carrots = carrots + 2;
cout << "now you have " << carrots << " carrots."<<endl;
cin.get();
cin.get();
return 0;
}
程序中有一个cin
,故在望控制台输入数据后,第一个cin.get()
读取输入的数据。第二条cin.get()
让程序暂停,直到键入Enter后才退出。
2.c++的两种传递消息的方式
类描述了对象的所有操作,要对特定的对象执行特定的操作,就要往对象发送一条消息。例如,如果希望cout
对象显示hello
,则需要给它发送hello
消息。c++提供了两种传递消息的方式:
- 使用类方法(函数调用)
- 重新定义运算符,如
cin
、cout
中>>
和<<
。
3.c++的程序模块是什么?
答:函数
4.make a demo to summary
// input a data suing two variables to a method ,and show it
#include<iostream>
void showTime(int h, int m);
int main()
{
using namespace std;
cout << "please enter hour number:";
int hour;
cin >> hour;
cin.get();// get first data
cout << "please enter a minute:";
int minute;
cin >> minute;
cin.get();//get second data
showTime(hour, minute);
cin.get();//keep dos to show
return 0;
}
void showTime(int hour, int minute)
{
using namespace std;
cout << "now times is " << hour << ":" << minute << endl;
}
网友评论