C++ 类的一些基本操作
通过new(delete)动态内存分配
class Teacher{
private:
char* name;
public:
Teacher(char* name){
this->name = name;
cout << "Teacher有参构造函数" << endl;
}
~Teacher(){
cout << "Teacher析构函数" << endl;
}
void setName(char* name){
this->name = name;
}
char* getName(){
return this->name;
}
};
void func(){
//C++
//会调用构造和析构函数
Teacher *t1 = new Teacher("jack");
cout << t1->getName() << endl;
//释放
delete t1;
//C
//Teacher *t2 = (Teacher*)malloc(sizeof(Teacher));
//t2->setName("jack");
//free(t2);
}
void main(){
func();
//数组类型
//C
//int *p1 = (int*)malloc(sizeof(int) * 10);
//p1[0] = 9;
//free(p1);
//C++
int *p2 = new int[10];
p2[0] = 2;
//释放数组 []
delete[] p2;
system("pause");
}
可以看出,C++这里越来越像JAVA了
Teacher *t1 = new Teacher("jack"); 来表示在堆内存中,创建一个指针。并且用delete去释放掉这块内存
static 静态属性和方法
class Teacher{
public:
char* name;
//计数器
static int total;
public:
Teacher(char* name){
this->name = name;
cout << "Teacher有参构造函数" << endl;
}
~Teacher(){
cout << "Teacher析构函数" << endl;
}
void setName(char* name){
this->name = name;
}
char* getName(){
return this->name;
}
//计数,静态函数
static void count(){
total++;
cout << total << endl;
}
};
//静态属性初始化赋值
int Teacher::total = 9;
void main(){
Teacher::total++;
cout << Teacher::total << endl;
//直接通过类名访问
Teacher::count();
//也可以通过对象名访问
Teacher t1("yuehang");
t1.count();
system("pause");
}
可以看出,可以直接通过类名访问静态变量/静态方法
下面说一下友元函数,作用在于,可以通过这个函数,访问类中定义的私有变量
class A {
//友元函数
friend void modify_i(A *p, int a);
private:
int i;
public:
A(int i) {
this->i = i;
}
~A() {
cout << "析构" << endl;
}
void myprint() {
cout << i << endl;
}
};
//友元函数的实现,在友元函数中可以访问私有的属性
void modify_i(A *p, int a) {
p->i = a;
}
void main() {
A* a = new A(10);
a->myprint();
modify_i(a, 20);
a->myprint();
delete a;
system("pause");
}
如上方法,就可以改变类中的私有变量的值,并且例子中运用到了C++中的动态内存,以及动态内存的释放的
下面说下友元类,说白了,就是友元类可以访问自己的类成员!!
class A {
//友元类
friend class B;
private:
int i;
public:
A(int i) {
this->i = i;
}
void myprint() {
cout << i << endl;
}
};
class B {
public:
//B这个友元类可以访问A类的任何成员
void accessAny() {
a.i = 30;
}
private:
A a;
};
首先在A中,申请友元类B,然后在B中,定义A为私有成员,就可以调用A成的成员变量了!!