1,Hello World
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;
cin >> name;
cout << "hello"<<name << endl;
return 1;
}
其中, 是C++特有的标准输入输出流;
using namespace std;是用标准命名空间;
return的值可以通过 echo $?查看;
2,简单的加法运算
#include <iostream>
using namespace std;
class add{
public:
double add1;
double add2;
double add3;
void plus (add other)
{
add1 = other.add1 + other.add1;
add2 = other.add2 + other.add2;
}
void plus1()
{
add3 = add1 + add2;
}
void printf()
{
cout << add1 << "+" <<add2 << endl;
}
void printf1()
{
cout <<add3<<"="<< add1 << "+" <<add2 << endl;
}
};
int main ()
{
add ad;
ad.add1 = 10;
ad.add2 = 20;
cout << sizeof (add) << endl;
ad.printf();
ad.plus(ad);
ad.printf();
ad.plus1();
ad.printf1();
return 0;
}
其中,类中定义的变量需要加上public才能够被外部函数访问到;
而类中只能定义变量与函数,不能够定义表达式;
在plus函数传参时,是把定义好有两个变量的ad类传输进去,其中,add1,add2还是之前定义的,other.add1和other.add2是传递进去的参数;
类的大小是类中每一个定义变量大小之和,函数并不占大小;
下图是打印出的结果:
3,C++的文件编译
C++程序在项目中一般分为定义类的头文件,实现功能函数的文件和主函数文件
下面举例说明:
(1),头文件
#include <string>
using std::string;
class Bill{
private:
string name;
int count;
double price;
public:
void Init (string n, int c,double p);
double Count();
void Print();
};
头文件包含类的定义,其中变量的定义是private,只能在类里的函数使用,函数是public;
(2),实现功能的文件
#include <iostream>
#include "Bill.h"
using namespace std;
void Bill::Init(string n,int c,double p)
{
name = n;
count = c;
price = p;
}
double Bill::Count()
{
return count * price;
}
void Bill::Print()
{
cout << name << "\t" << count << "\t" << price << endl;
}
其中,自己写的头文件需要用双引号引起来;
使用头文件定义函数的时候,需要用“类名 ::”来指明;
(3),主函数文件
#include <iostream>
#include "Bill.h"
using namespace std;
int main ()
{
Bill b;
b.Init("apple",6,2.1);
b.Print();
cout << "Count is " << b.Count() << endl;
return 0;
}