在实际开发过程中,不会将类的名称和类的实现放到一起。
静态数据成员,就不会仅仅存在于当前的对象中,而是属于类的。
如果没有类的静态成员变量,如果想使用的话。
#include
#include <Windows.h>
#include
#include <string.h>
using namespace std;
int HumanCount ;
// 定义一个“人类”
#include
class Human {
public:
Human();
Human(int age, int salary);
Human(const Human&); //不定义拷贝构造函数,编译器会生成“合成的拷贝构造函数”
void eat();
void sleep();
void play();
void work();
int getAge();
int getSalary();
void setAddr(const char *newAddr);
const char* getAddr();
int getHC();
private:
char name ;
int age ;
int salary;
char *addr;
//static int HC ;
};
//int Human::HC = 0 ;
Human::Human() {
age = 18;
salary = 30000;
HumanCount ++ ;
//HC++;
cout<<&HumanCount<<endl;
}
Human::Human(int age, int salary) {
cout << “调用自定义的构造函数” << endl;
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->salary = salary;
addr = new char[64];
strcpy_s(addr, 64, "China");
HumanCount ++ ;
//HC++ ;
cout <<&HumanCount<<endl;
}
Human::Human(const Human &man) {
cout << “调用自定义的拷贝构造函数” << “参数:” << &man
<< " 本对象:" << this << endl;
age = man.age; //this是一个特殊的指针,指向这个对象本身
salary = man.salary;
name = man.name;
// 深度拷贝
addr = new char[64];
strcpy_s(addr, 64, man.addr);
HumanCount++;
cout<<&HumanCount<<endl;
}
void Human::eat() {
cout << “吃炸鸡,喝啤酒!” << endl;
}
int Human::getHC() {
//cout<<HC<<endl;
//return HC;
}
void Human::sleep() {
cout << “我正在睡觉!” << endl;
}
void Human::play() {
cout << "我在唱歌! " << endl;
}
void Human::work() {
cout << “我在工作…” << endl;
}
int Human::getAge() {
return age;
}
int Human::getSalary() {
return salary;
}
void Human::setAddr(const char *newAddr) {
if (!newAddr) {
return;
}
strcpy_s(addr, 64, newAddr);
}
const char* Human::getAddr() {
return addr;
}
void test(Human man) {
cout << man.getSalary() << endl;
}
void test2(Human &man) { //不会调用拷贝构造函数,此时没有没有构造新的对象
cout << man.getSalary() << endl;
}
Human test3(Human &man) {
return man;
}
Human& test4(Human &man) {
return man;
}
void test(){
Human tmp1;
Human tmp2;
cout<<HumanCount<<endl;
}
int main(void) {
Human h1(25,3000);
Human h2;
test();
h1.getAddr;
cout<<HumanCount<<endl;
system(“pause”);
return 0;
}
使用场景分布在 一些类需要共同使用的场景。
相应 有静态数据,就有静态函数。地址使用范围和静态数据是一样的。