1.当一个标识符(变量或函数)被声明为 static 时,它只在定义它的编译单元(文件) 内可见,其他文件无法访问。
include
include
using namespace std;
class Human {
public:
Human(int age,int number,string addr);
~Human();
void getCount();
private:
static int count;//需要在外部定义------------------------------------------>>重要
int age;
int number;
string* addr;
};
int Human::count = 0;//在此处定义------------------------------------------>>重要
Human::Human(int age, int number,string addr) {
this->age = age;
this->number = number;
this->addr = new string(addr);
this->count++;
cout << age << " " << number << " " << *(this->addr) << endl;
cout << "构造函数" << endl;
}
Human::~Human() {
delete addr;
cout << "析构函数" << endl;
}
void Human::getCount() {
cout << this->count << endl;
}
int main() {
Human h1(1,2,"A");
Human h2(5, 4, "B");
h1.getCount();
h2.getCount();
}