这是头文件
#pragma once
#include "iostream"
#include "cstring"
using namespace std;
class computer {
private:
char* brand;
int price;
public:
//===============================【类的赋值函数】==================================
// 描述:当把类A赋值给类B时,类B会调用这个函数来复制类A内容。
// 如果用编译器默认的类的赋值函数可能会出现几种错误情况
// 1.指针赋值,如果不自己申请内存,而是直接将指针指过去,可能会出现野指针的情况。
// 2.如果const变量成员,如果用默认赋值函数会出错,因为赋值函数会在里面为const成员赋值。
// 提示:定义在类中的static变量在这个类中是共用的。
//=============================================================================
/*
//默认情况编译器会自动给我写成这样,但是这样【会有问题】
computer(const computer &ct) {
brand = ct.brand; //在这里就会有问题,一旦类B被释放了,类A的brand也会跟着被释放。
price = c.price; //这里是没有问题的。
}
*/
//最好的办法是我们自己写出赋值函数
computer(const computer &ct) {
//这样就没问题了。
int len = strlen(ct.brand) + 1;
brand = new char[len];
strcpy_s(brand,len,ct.brand);
brand = ct.brand;
}
//=========================【构造函数】==========================
// 描述:构造函数
//===============================================================
computer(const char *brand, const const int price) {
int len = strlen(brand) + 1;
computer::brand = new char[len];
strcpy_s(computer::brand,len,brand);
}
//=========================【其它函数】==========================
// 描述:类的其它函数
//===============================================================
void printf() {
static int cnt = 0;
cnt++;
cout << "brand=" << brand << " price=" << price << "static变量"<<cnt<<endl;
}
};
这是源文件
#include "head.h"
int main() {
computer ct1("联想",5000);
cout << "====================ct1=======================" << endl;
ct1.printf();
cout << "====================ct2=======================" << endl;
computer ct2 = ct1;
ct2.printf();
//在出CT1就可以明白,static变量在computer类中是共用的,无论以后定义了多少个computer类,static变量都是共用的。
cout << "======================ct1=======================" << endl;
ct1.printf();
return 0;
}