c++基础
c++与c的区别
c是面向过程的语言
C++是面向对象的语言,与c的标志性不同的是,多了面对对象的属性和一套好用的标准库STL
STL是一套封装好的类与函数的库
c++语法
#include<iostream>//头文件
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
//标准命名空间std
//命名空间:包含变量名、函数方法名。解决了不同工程的变量函数等命名冲突的问题
//std:C++标准库所在的命名空间,其中需要用到的是cout、cin、endl、string等。
int main(){
ios;
int a;
cin >> a;
cout << a ;
}
c的库在c++中使用
后缀.h变成前缀c
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>
构造函数
构造函数格式
构造函数格式:
构造体名(参数列表){
参数赋值
}
结构体的构造函数和结构体同名
结构体的构造函数在创建对应结构体变量时自动调用
当写了构造函数时,系统默认无参构造将会消失,此时创建结构体变量必须使用你提供的构造函数
#include<iostream>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
struct node{
int a,b;
node(int _a = 0,int _b = 0){
a = _a;
b = _b;
}
};
int main(){
ios;
node node1(1,2);
node node2 = node(2,3);
node* node3 = new node(1,2);
node node4;//需要初始化;
cout << node1.a << " " << node2.a<< " " << (*node3).a << " " << node3->a << " " << node4.a;
return 0;
}
流输入 流输出
#include<iostream>
#include<string>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
int main(){
ios;//加速//使c++输入速度和c相近
int a;
char b;
string s;
cin >> a >> b >> s;
cout << a << endl;
cout << b << endl;
cout << s << endl ;
return 0;
}
输入一行方式
#include<iostream>
#include<string>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
int main(){
ios;
string s;
char a[100];
getline(cin,s);//输入一行
cin.getline(a,1000);//1000为读入上限 相当于gets(cstring);
cout << s << endl ;
cout << a << endl ;
return 0;
}
输入到文件末尾
#include<iostream>
#include<string>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
int main(){
ios;
int n ,m;
while(cin >> n >> m){//循环读入知道文件结束(判定EOF结束循环)
}
return 0;
}
引用类型
#include<iostream>
#include<string>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
void c_swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void cpp_swap(int &a, int &b) {//格式:
//在函数的参数列表中,形参的前面加上&。表示对传入的变量做引用
//引用的变量不会创建一个新的副本,可以看作此时的变量即为原变量
int t = a;
a = b;
b = t;
}
int main() {
ios;
int a, b;
cin >> a >> b;
cpp_swap(a, b);
cout << a << " " << b;
return 0;
}
函数重载
#include<iostream>
#include<string>
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
void fun() {
cout<<"fun()"<<endl;
}
void fun(int a){
cout<<"fun(int a)"<<endl;
}
void fun(int a, int b){
cout<<"fun(int a,int b)"<<endl;
}
int main() {
ios;
fun();
fun(1);
fun(1,2);
return 0;
}
新增数据类型
bool (布尔类型)
Bool类型的变量仅有两种值 : true(1) 与 false(0)
string (字符串类型)
主要用于字符串处理,可以使用输入输出流方式直接进行string操作,也可以通过文件等手段进行string操作,比char数组有更多封装好的方法。(需要添加头文件 < string >)。