代码规范
using namespace std;//表示名字空间,表示使用名字的空间,std标准空间,就是一个范围
输入输出流
int a;
double b;
cin >> a >> b;
cout << a << " " << b << endl;
一些头文件
#include<string>//可以直接实现string的链接,输入输出
#include<iostream>
#include<string>
using namespace std;
int main(){
string s1 = "jslkdjfl";
string s2;
cin >> s2;
string s4 = s1 + s2;
cout << s4;
return 0;
}
类
#include<iostream>
using namespace std;
class CMyTime{
private:
int h;
int m=20;
int s;
public:
void setTime(int a,int b,int c){
this->h = a;//cpp的this是一个指针,需要用它指向其成员
this->m = b;
this->s = c;
}
void showTime(){
cout << this->h << ":" << this->m << ":" <<this->s<<endl;
}
};
注意cpp的private和public不是单独写的。
#include <iostream>
#include"CMyTime.cpp"//同一个工程下调用使用双引号
int main(int argc, char** argv) {
CMyTime t1;
t1.setTime(7,40,30);
t1.showTime();
return 0;
}
构造函数
构造函数名和类名一致,和java类似,没有返回值,在创建类的时候添加参数,自动执行构造函数
构造函数一定要放在public中
构造函数默认为空,当添加了不同的构造参数后,程序会根据初始化时存入的参数不同自动进行调用相应的构造函数(重载)
当添加了带参数的构造函数后,原无参构造函数被覆盖,如果使用无参初始化,需要另外写一个无参构造函数
#include<iostream>
using namespace std;
class CMyTime{
private:
int h;
int m=20;
int s;
public:
CMyTime(int a,int b,int c){//三个参数的构造函数
h = a;
m = b;
s = c ;
}
CMyTime(){//无参构造函数
}
CMyTime(int a,int b){//两个参数的构造函数
h = a;
m = b;
s = 0;
}
void setTime(int a,int b,int c){
this->h = a;
this->m = b;
this->s = c;
}
void showTime(){
cout << this->h << ":" << this->m << ":" <<this->s<<endl;
}
};
new的使用
new创建了新的空间并且返回一个指向此空间的指针
int *a = new int(6);//new一个int型,值为6,并把它的指针赋值给a
int *a = new int[6];//开辟6大小的空间,注意中括号和小括号不同