析构不可以进行重载
拷贝函数 构造函数是对象初始化的时候调用
#include<iostream> #include<cmath> #pragma warning (disable :4996) using namespace std; class Teacher { public: Teacher(int id, char *name) { cout << "int,char *" << endl; m_id = id; int len = strlen(name); m_name = (char *)malloc(len + 1); strcpy(m_name, name); } void printT() { cout << "id = " <<m_id << ",name = " << m_name << endl; } //显示提供一个拷贝构造函数,来完成深拷贝动作 Teacher(const Teacher &another) { m_id = another.m_id; //深拷贝动作 int len = strlen(another.m_name); m_name = (char *)malloc(len + 1); strcpy(m_name, another.m_name); } ~Teacher() { cout << "~Teacher().." << endl; if (m_name != NULL) free(m_name); m_name = NULL; } private: int m_id; char *m_name; }; int main(void) { Teacher t1(1, "zhang3"); t1.printT(); Teacher t2(t1);//t2的默认拷贝构造 t2.printT(); system("pause"); return 0; }构造函数中调用构造函数是危险的行为
new 和delete 类似C中的malloc和free
#include <iostream> #include <string> using namespace std; class test { private: static int m_value; //定义类的静态成员变量 public: static int getValue() //定义类的静态成员函数 { return m_value; } }; int test::m_value = 12; //类的静态成员变量需要在类外分配内存空间 int main() { test t; cout << t.getValue() << endl; system("pause"); }
int test::m_value = 12; //类的静态成员变量需要在类外分配内存空间
在c++中可以定义静态成员变量 静态成员变量属于整个类所有 静态成员变量的生命周期不依赖于任何对象 可以通过类名直接访问公有静态成员变量 所有对象共享类的静态成员变量 可以通过对象名访问公有静态成员变量 静态成员变量的特性 在定义时直接通过static关键字修饰 静态成员变量需要在类外单独分配空间 静态成员变量在程序内部位于全局数据区
