#include <iostream>
#include <string>
using namespace std;
class A
{
private:
static int a;
const int b;
char* c;
public:
//const类型需要用初始化列表进行初始化,初始化列表提供的值作为构造const对象的初值
//在构造函数中为指针分配内存空间
A(int bTemp,const char *p = nullptr) :b(bTemp)
{
if (p)
{
c = new char[strlen(p) + 1];
memcpy(c, p, strlen(p) + 1);
}
else
{
c = new char[1];
*c = '\0';
}
}
//拷贝构造函数
A (const A &temp):b(temp.b)
{
//strlen计算指针指向内存空间的长度
//分配内存空间,使成员变量指向该内存空间
c = new char[strlen(temp.c) + 1];
memcpy(c, temp.c, strlen(temp.c) + 1);
}
//赋值构造函数
A& operator=(const A& temp)
{
if (c == temp.c)
return *this;
c = new char[strlen(temp.c) + 1];
memcpy(c, temp.c, strlen(temp.c) + 1);
return *this;
}
~A()
{
delete []c;
}
void print()
{
cout <<"static静态变量的值为:"<< a << endl;
cout << "const常量的值为:" << b << endl;
cout << "指针指向的值为:" << c << endl;
}
};
int A::a = 1;
int main()
{
//使用构造函数构造一个对象object1
const char* p1 = "abcde";
A object1(2, p1);
object1.print();
const char* p2 = "abcdefg";
A object2(3, p2);
//使用拷贝构造函数构造一个对象object3
A object3(object2);
object3.print();
//构造一个对象object4
//用object4对object3赋值
const char* p3 = "abcdefghijk";
A object4(4, p3);
object3 = object4;
object3.print();
return 0;
}
程序运行结果