静态数据成员的使用范围

在实际开发过程中,不会将类的名称和类的实现放到一起。
静态数据成员,就不会仅仅存在于当前的对象中,而是属于类的。

如果没有类的静态成员变量,如果想使用的话。在这里插入图片描述
#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;
}

使用场景分布在 一些类需要共同使用的场景。
相应 有静态数据,就有静态函数。地址使用范围和静态数据是一样的。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值