1.
使用vim创建后缀为cpp的文件,使用g++编译
vim hello.cpp
g++ hello.cpp -o hello
如果使用gcc编译的话:gcc hello.cpp -lstdc++ -o hello
2.
#include <iostream> //头文件
using namespace std; //using 是申明,namespace是命名空间,作用是防止定义的变量函数重名
int main()
{
cout<<"hello world !"<<endl; //cout是输出,cin是输入,endl是换行,这写都是在std类里面
return 0;
}
3.
c 语言中所有变量的定义在函数开头;
c ++ 中那边用到只要在用之前定义就行
bool布尔类型只有两种情况,0和1 就是false 和true
指针和0的比较
if(ptr == NULL)
浮点和0比较
if((f_num >-0.000001)&&(f_num < 0.000001))
float保留三位小数输出
float f_num = 98.5
printf("%.3f",f_num);
4.
::是域运算符
命名空间用namespace定义,格式如下:
namespace 命名空间名
{
命名空间生命内容
} //最后不需要分号;
using namespace std;
{
void print()
{
cout<<"nsA"<<endl;
}
}
{
void print()
{
cout<<"nsB"<<endl;
}
}
int main()
{
nsA::print(); //使用nsA命名空间内的print
nsB::print(); //使用nsB命名空间内的print
return 0;
}
#include <iostream>
using std::string;
using std::cout;
{
string temp;
cin>>temp;
cout<<temp;
return 0;
}
int var = 10;
}
float var = 12.12;
}
{
{ //这边的两组打过好不可以省略,大括号限制using的作用域
using namespace nsA;
cout<<"nsA var ="<<var<<endl;
}
using namespace nsB;
cout<<"nsB var ="<<var<<endl;
}
return 0;
}
double max (double , double);
int max(int ,int , int );
{
int a = 2,b = 4, c = 5, d;
double m = 11.1, n = 13.3,j;
cout<<a<<","<<b<<",max = "<<d<<endl;
cout<<m<<","<<n<<",max = "<<j<<endl;
cout<<a<<","<<b<<","<<c<<",max = "<<d<<endl;
return 0;
}
{
return x > y ? x:y;
}
{
return x > y ? x:y;
{
int temp;
temp = (x > y ? x:y);
return temp > z ? temp : z;
}
如果函数只有定义,则默认值可以出现在函数定义中。
函数调用时,实参与形参按从左到右的顺序进行匹配
函数既有定义又有声明时,声明时指定后,定义后就不能再指定默认值
{
cout<<x<<","<<y<<","<<z<<endl;
}
{
int x , y , z;
cout<<"x y z"<<endl;
cin >>x>>y>>z; //输入2 4 6
point(x); // 输出2 0 0
point(x,y); //输出 2 4 0
point(x,y,z); //输出2 4 6
}
inline <类型标识><函数名>(形参列表)
{
函数体
}
using namespace std;
int main()
{
int a[10]={0};
int i;
cout<<"please input 10 numbers!"<<endl;
for(i = 0;i < 10; i++)
{
cin>>a[i];
}
int temp = a[0];
for(i = 0;i < 10;i++)
{
temp = max(temp ,a[i]);
}
cout<<"in 10 numbers max is:"<<temp<<endl;
return 0;
}
{
return x >= y? x:y;
}
#include <string.h>
#include <iostream>
using namespace std;
public: //这里public不能少
//char const *name;
char name[20];
int age;
float score;
{
// printf("%s,%d,%.3f\n",name,age,score);
cout<<name<<","<<age<<","<<score<<endl; //连续输出
}
};
{
class student stu1;
//stu1.name = "xiaoming"; //如是指针就直接把字符串付给他就行
strcpy(stu1.name,"xiaoming"); //just use strcpy(); 若是数组就需要使用strcpy
stu1.age = 19;
stu1.score = 98.5;
stu1.say(); //可以直接调用类里面的say()函数
return 0;
}
const char *name; //c++中可以在类里面有函数c语言中不可以
int age;
float score;
{
struct student stu1;
stu1.name = "xiaoming";
stu1.age = 19;
stu1.score = 98.5;
printf("%s,%d,%.3f\n",stu1.name,stu1.age,stu1.score);
return 0;
}
******************************************
new ,delete
1. malloc ,free
int *p = (int *)malloc(sizeof(int)*10);
free(p);
2. new,delete
2.1 单个类型
int *p = new int;
delete p
2.2 希望连续分配的数据
int *p = new int[10];
delete[] p;