1.1 编写一个简单的c++ 程序 Writing a simple c++ program
每个程序都会有一个或者几个function,一定会有一个main function,下面是一个简单的mainfunction:
int /*1retun type*/ main/*2function name*/()/*3parameter list*/
{
return 0;/*Note the semicolon*/
}/*4function body*/
main 函数的 返回类型必须为int,其返回值用来指示状态,0表示成功,非0表示错误状态,本例中的参数为空,函数体是在curly brace内的block of statements。
1.1.1 Compiling and executing编译、运行
常见源文件名:cc,cxx,cpp,cp,c
可执行文件:window:exe,Unix:out
$ g++ -o prog1 prog1.cc/*g++是GNU编辑器的运行命令,-o xxx指定可执行文件名*/
X:\path\> cl /EHsc prog1.cpp/*cl是VS的运行命令,/EHsc是编译器选项*/
1.2 输入输出
c++使用iostream来提供IO机制,包括4个IO对象,cin,cout,cerr(输出警告和错误), clog
看下面的程序
#include <iostream>//头文件
int main()
{
std::cout <<"2numbers,please"<< std::endl;/*输出运算符<<(output operator),endl是操纵符manipulator*/
int v1=0,v2=0;
std::cin>>v1>>v2;/*std::指出namespace为std,“::”是作用于运算符scope operator*/
std::cout<<"the sum of "<<v1<<"and"<<v2<<"is"<<v1+v2<<std::endl;
return 0;
}
1.3 注释 comments
/*
*这种形式一般是多行注释
*
*/
//这种一般是单行注释,可以用//来注释掉/**/
1.4 控制流
1.4.1 while
while(condition){
statement
}
1.4.2 while
for循环,包含init-statement,condition及expression三个部分
for(int val=1;val<=0;++val)
sum+=1;//注意分号的出现位置,一共出现了三次,while的初始化需要在循环前方进行,多语句用{}
1.4.3 读取数量不定的输入数据
#include<iostream>
int main()
{
int sum=0,value=0;
while(std::cin>>value)
sum+=value;
std::cout<<"sumis"<<sum<<std::endl;
return 0;
}//文件结束符windows:Ctrl+Z,enter或return;Unix或Mac OS Ctrl+D
1.5 类
这里并没有详细的介绍类,只是做了以下几点说明:
1. 类的头文件:.h .hpp .hxx 通常以类名来命名
2. item1.isbn()这样的形式来调用类的成员函数
总结:
本文介绍了C++编程的基础知识,包括简单程序的编写、编译与运行流程、输入输出操作、控制流语句以及类的基本概念。
33万+

被折叠的 条评论
为什么被折叠?



