一.基本格式
头文件#include<iostream>
using namespace std;
int main
{
}
二.输入输出
1.cout输出
#include <iostream>
using namespace std;
int main()
{
int a=123;
double b=3.13;
const char *p="hello";
cout<<"a="<<a<<"b="<<b<<"p="<<p<<"\n";
while(1);
}
运行
a=123b=3.13p=hello
2.cin输入
#include <iostream>
using namespace std;
int main()
{
int a=123;
double b=3.13;
char buf[10];
cin>>a>>b>>buf;
cout<<"a="<<a<<"b="<<b<<"buf="<<buf<<"\n";
return 0;
}
键盘输入2 0.1 cxy
输出a=2b=0.1buf=cxy
三.结构体定义和类
1.结构体
(1)先构造后定义
例如
struct student
{
int number;
char name[5];
};
int main()
{
struct student stu1;
struct student stu2;
}
(2)构造的同时定义
struct student
{
int number;
char name[5];
}stu1,stu2;
(3)构造的同时进行定义,省略类型名,不能在定义新的变量了
struct
{
int number;
char name[5];
}stu1,stu2;
(4)typrdef改名
typedef struct student
{
int number;
char name[5];
}stu;
以后的数据类型变成stu不再是student
c:结构体,数据可以随意访问,方法的指向也可能发生变化
因此c++我们提出了更多功能的类
2.类
c++
class demo{
public: //共有权限
private: //私有的
protected: //保护的
};
c++的类可以在内部定义函数题了
并且分为公共和私有的部分,公共可以调用,私有却不行,因此也避免了c语言里一些结构体里面的数据可以随意访问的缺点
四.构造函数
构造函数:类对象生成自动调用的函数
普通构造{
默认普通构造,没有参数和返回值
}
拷贝构造{
浅拷贝
深拷贝
}
移动构造{
有临时对象产生时使用
}
#include <iostream>
#include <cstring>
using namespace std;
class arr
{
public:
//普通构造
arr(char *p=nullptr)
{
cout<<"原-normal"<<endl;
str=new char[strlen(p)+1];
strcpy(str,p);
}
//拷贝构造 浅
/* arr(const arr &obj)
{
cout<<"浅-cpy"<<endl;
str=obj.str;
}
*/
//拷贝构造 深
arr(const arr &obj)
{
cout<<"深-cpy"<<endl;
str=new char[strlen(obj.str)+1];
strcpy(str,obj.str);
}
//移动构造
arr( arr &&obj)
{
cout<<"移动构造"<<endl;
str=obj.str;
obj.str=nullptr;
}
//获取返回值
char*getval()
{
return str;
}
//设置值
void setval(const int id,const char data)
{
str[id]=data;
}
private:
char*str;
int len;
};
int main()
{
char buf[10]="world";
arr A="hello";//普通构造
//arr B=A;//浅拷贝
// arr C=A;//深拷贝
arr D=buf;
//A.setval(0,'a');
cout<<A.getval()<<endl;
//cout<<B.getval()<<endl;
// cout<<C.getval()<<endl;
cout<<D.getval()<<endl;
return 0;
}
tips:浅拷贝和深拷贝只能由一个存在,不然会存在歧义
移动拷贝必须由普通构造才能实现