new int;
new int[10];
delete p;
delete [] p;
new 和 delete 是关键字也是运算符
new 的时候是先得到空间,然后初始化; delete 的时候是先析构,然后收回空间
在动态内存分配的时候,程序内部有一个数据表来记录你每次申请的内存的首地址和大小
delete p; 的时候程序先在数据表里去查找p,找到后删除数据表中p的这一项并回收内存
int *a = new int[10]; a++; delete a; 会运行出错,因为在数据表中找不到a
student *p = new student[10];
在做delete p;
的时候只析构了p所指的那个对象,后面9个没有析构,但是整个分配空间都被收回了,因为数据表中记录的空间的大小就是这么多
delete [] p; 就会全部析构
Tips for delete:
1: don't use delete to free memory that new didn't allocate
2: don't use delete to free the same block of memory twice in succession
3: using delete [] if you used new [] to allocate an array
4: use delete(no brackets) if you used new to allocate a single entity
5: it's safe to apply delete to the null pointer(nothing happens)
一个类的private成员只有这个类里面的成员函数才可以访问
同一个类的对象之间是可以互相访问私有成员的
这种检查机制只有在编译的时候才会做,在运行的时候是不会的,这是因为当编译完以后,生成的东西已经不属于面向对象了
friend 的授权是在编译时刻检查的
A声明B是自己的友元,那么B就可以访问A中的私有成员,但是A不能访问B的私有成员
在c++ struct和class是一样的,但是有细微的差别
没有声明访问属性:
class defaults to private
struct defaults to public
两者只有这一点区别
在C++一般首选class
自己写了构造函数,编译器就不会再自动生成一个default constructor
initalize list (初始化列表)
可以初始化任何类型的数据
private:
const int x, y;
public:
Print(int xa, int ya) : x(xa), y(ya) {}
这种写法与放在{}内是有区别的,这个初始化早于构造函数被执行
Student::Student(string s) name(s) {} // 这种叫做初始化
Student::Student(string s){ name = s; } // 这种叫做赋值
不是说写在构造函数里面就是初始化
建议类里面的所有成员变量都用 initalizer list 来初始化,而不要在构造函数里面做赋值
learning record code:
#include <iostream>
using namespace std;
class A{
private:
int i;
int *p;
public:
A(){ p = 0; cout << "constructed" << endl; } // 构造函数和析构函数不能是私有的
~A(){ delete p; cout << "destructed i = " << i << endl; }
void set(int i){ this->i = i; }
void f() { p = new int; cout << "Hello" << endl; };
};
struct X; // 前向声明
struct Y {
void f(X *);
};
struct X {
private:
int i;
public:
void initialize();
friend void g(X*, int); // global friend
friend void Y::f(X*); // struct member friend
friend struct Z; // entire struct is a friend
friend void h();
};
void X::initialize()
{
i = 0;
}
void g(X *x, int i)
{
x->i = i;
cout << "in g() i = " << x->i << endl;
}
void Y::f(X *x)
{
x->i = 47;
cout << x->i << endl;
}
struct Z {
private:
int j;
};
int main()
{
// A *p = new A[10];
// for(int i=0; i<10; i++)
// {
// p[i].set(i);
// }
// delete [] p;
X tm;
Y ym;
tm.initialize();
ym.f(&tm);
g(&tm, 10);
return 0;
}