ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

static

static

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();

}

返回列表