const数据成员:它的作用是不能随便修改该类数据成员的值,要想赋值只能在初始化列表中进行赋值。
const成员函数:const成员函数中不能修改函数内任何数据成员的值。
const对象:仅能访问const成员函数,其他普通成员函数不可以方法。
Human.h
#pragma once
#include <iostream>
#include <string>
#include <Windows.h>
#define ADDR_LEN 64
using namespace std;
class Human {
public:
Human();
Human(string, int, int, string);
Human(const Human &);
Human &operator=(const Human &);
int getAge();
int getHeight();
void desprition() const;
void setAddr(const char *);
static int Humancount();
~Human();
private:
string name;
const string bloodType; // const 数据成员
char *addr;
int age;
int height;
static int humanCount;
};
Human.cpp
#include "Human.h"
#include <iostream>
int Human::humanCount = 0;
Human::Human(): bloodType("未知") { // 默认构造函数
name = "张三";
age = 24;
height = 175;
// bloodType = "A";
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, "China");
humanCount++;
}
Human::Human(string name, int age, int height, string bldtype):bloodType(bldtype){
// 自定义构造函数
this->name = name;
this->age = age;
this->height = height;
// this->bloodType = bldtype;
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, "China");
humanCount++;
}
Human::Human(const Human &other){
// 拷贝构造函数
this->name = other.name;
this->age = other.age;
this->height = other.height;
// this->bloodType = other.bloodType;
this->addr = new char[ADDR_LEN];
strcpy_s(this->addr, ADDR_LEN, other.addr);
humanCount++;
}
Human &Human::operator=(const Human &other){
// 赋值构造函数
if (this == &other) {
return *this;
}
delete[] addr;
this->name = other.name;
this->age = other.age;
this->height = other.height;
// this->bloodType = other.bloodType;
this->addr = new char[ADDR_LEN];
strcpy_s(this->addr, ADDR_LEN, other.addr);
return *this;
}
int Human::getAge() {
return age;
}
int Human::getHeight() {
return height;
}
void Human::setAddr(const char *addr) {
strcpy_s(this->addr, ADDR_LEN, addr);
}
void Human::desprition() const
{
cout<< "name:" << name <<
" age:" << age <<
" height:" << height <<
" addr:" << addr <<
" bloodType:" << bloodType << endl;
}
int Human::Humancount() {
cout << "Total: " << humanCount << " persons" << endl;
return humanCount;
}
Human::~Human() {
humanCount--;
delete[] addr; // Use delete[] for array
}
main.cpp
#include "Human.h"
int main() {
Human h1;
Human h2("李华", 26, 176, "B");
const Human h3(h2); // const 对象只能访问const成员函数,但是const成员函数不能修改里面的数据成员
h2.setAddr("American");
h1.desprition();
h2.desprition();
h3.desprition();
Human::Humancount(); // 类访问静态成员函数
h3.Humancount(); // 对象也可以访问静态成员函数
system("pause");
return 0;
}
运行结果: