一、简单C++程序
int main()
{
return 0;
}
二、初窥输入输出
// IO库演示程序
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1, v2;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}
三、注释
2.1 多行注释:使用注释对/**/,同时,在注释的每一行以星号开始,指明整个范围是多行注释的一部分。
任何允许有制表符、空格或换行符的地方都允许放注释对。
2.2 单行注释:使用//
2.3 通常最好是将一个注释块放在所解释代码的上方!
2.4 注释对不可嵌套
四、控制结构
// while结构形式
while (condition) while_body_statement;
// for结构形式
for(expression1; expression2; expression)
for_body_statement;
// if结构形式
if(condition)
if_body_statement;
上述只是给出来几个简单的控制结构,这里只是作为简单了解,后续再分别进行详细说明
五、类
1、C++中,我们通过定义类来定义自己的数据结构
实际上,C++设计的主要焦点就是使所定义的类类型(class type)的行为可以像内置类型(内置类型,即该类型是由C++语言定义的)一样自然!
2、使用类的时候,我们不需要指定这个类是怎样实现的,相反,我们需要知道的是:这个类能够提供什么样的操作!
3、对于自定义的类,必须使得编译器可以访问和类相关的定义。
4、通常文件名和定义在头文件中的类名是一样的。通常后缀名是.h,但也有用.h、.hpp和.hxx这种后缀的。
5、当使用自定义头文件时,我们采用双引号(””)把头文件包含进来。
6、成员函数
成员函数是由类定义的函数,有时称为类方法(method)。
当调用成员函数的时候,(通常)指定函数要操作的对象,语法是使用点操作符(”.”),左操作符必须是类类型,右操作符必须指定该类型的成员。
六、C++程序示例
#include <iostream>
#include <fstream>
#include "Sales_item.h"
int main()
{
// declare variables to hold running sum and data for the next record
Sales_item total,trans;
// is there data to process ?
if (std::cin >> total) {
// if so, read the transaction records
while (std::cin >> trans)
{
if (total.same_isbn(trans))
{ // match: update the running total
total += trans;
}
else
{ // no match: print & assign to total
std::cout << total << std::endl;
total = trans;
}
}
// remember to print last record
std::cout << total << std::endl;
}
else
{ // no input!,warn the user
std::cout << "No Data?!" << std::endl;
return -1; // indicate failure
}
return 0;
}
该示例程序基本涵盖了本节提交的各个知识点,可以作为简单了解,后续会逐一深入详细说明。