前置和后置形式的自增运算符
1 #include <iostream>
2
3 void test0(){
4 int k = 0;
? 5 &(++k);//是一个左值
6 int p=0;
? 7 &(p++);//是一个右值
8 }
9
10 int main()
11 {
12
13 return 0;
14 }
new表达式工作步骤
1.调用一个operator new库函数开辟未类型化的空间 void* operator new(size_t);
tips:size_t表示是一个无符号整型
2.在未类型化的空间上调用构造函数,初始化对象成员
3.返回相应类型的指针
delete表达式工作步骤
1.调用相应类型的析构函数
2.调用operator delete库函数回收对象所在的空间 void operator delete(void*);
结论:调用析构函数,并不是回收对象所在的空间
要求:只能生成栈对象
一个类只能创建在栈上的对象,不能创建位于堆上的对象
1.必须确保构造函数和析构函数都要放在public区域
2.将类中的operator new库函数放在private区域
1 #include <iostream>
2 #include <string.h>
3 using std::cout;
4 using std::endl;
5
6 class Student
7 {
8 public:
9 Student(const char* name,int id)
10 :_name(new char[strlen(name)+1]())
11 ,_id(id)
12 {
13 strcpy(_name,name);
14 cout<<"Student(const char*,int)"<<endl;
15 }
16 void print()
17 {
18 cout<<"姓名"<<this->_name
19 <<"学号"<<this->_id<<endl;
20 }
21 void release()
22 {
23 delete this;
24 }
25
26 ~Student(){
27 if(_name){
28 delete [] _name;
29 _name =nullptr;
30 }
31 }
32 private:
33 void* operator new(size_t n){
34 cout<<"operator new(size_t)"<<endl;
35 return malloc(n);
36 }
37
38 void operator delete(void *p)
39 {
40 cout<<"operator delete(size_t)"<<endl;
41 free(p);
42 }
43
44 private:
45 char* _name;
46 int _id;
47 };
48
49 void test1()
50 {
51 //要求生成栈对象
52 Student s1("xiaoming",100);
53 s1.print();
54
55
56 }
57
58 int main()
59 {
60 test1();
61 return 0;
62 }
运行结果
要求:只能生成堆对象
一个类只能创建堆上的对象,不能创建位于栈上的对象
1.不能创建栈对象,只要构造函数和析构函数中的某一个放在private区域即可
2.new表达式的工作步骤不能有障碍,所以构造函数必须放在public区域
结论:只需要将析构函数放在private区域即可
#include <iostream>
#include <string.h>
using std::cout;
using std::endl;
class Student
{
public:
Student(const char* name,int id)
:_name(new char[strlen(name)+1]())
,_id(id)
{
strcpy(_name,name);
cout<<"Student(const char*,int)"<<endl;
}
void print()
{
cout<<"姓名"<<this->_name
<<"学号"<<this->_id<<endl;
}
void release()
{
delete this;
}
private:
~Student(){
if(_name){
delete [] _name;
_name =nullptr;
}
}
public:
void* operator new(size_t n)
{
cout<<"operator new(size_t)"<<endl;
return malloc(n);
}
void operator delete(void *p)
{
cout<<"operator delete(void*)"<<endl;
free(p);
}
private:
char* _name;
int _id;
};
void test1()
{
//要求生成堆对象
Student *s1= new Student("xiaoming",100);
s1->print();
// Student s2("xiaohong",101);//只能生成堆对象
s1->release();
}
int main()
{
test1();
return 0;
}
运行结果
c++IO流
通用IO:istream/ostream
类istream cin;标准输入流对象 类ostream cuot;标准输出流对象 类ostream cerr 标准错误对象
文件IO:类ifstream、类ofstream、类fstream
字符串IO:类istringstream、类ostringstream、类stringstream
流的状态
所有的流都具有状态
goodbit:流是有效状态时,才能进行正常工作 cin.good();
badbit:不可恢复的错误 cin.bad();
eofbit:到达流的末尾 cin.eof();
failbit:可以恢复的错误 cin.fail();
测试结果
重置流的状态
cin.clear();
清空缓冲区
is.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
缓冲区
分类:1.全缓冲:当缓冲区满的时候,数据就会直接输出
2.行缓冲:当碰到一个‘\n’时,就会直接输出
3.非缓冲:直接输出cerr