1:本月8.9.10.19日四天学习了黑马程序c++课程类和对象中构造函数和析构函数,函数的分类及调用,构造函数调用规则,深拷贝与浅拷贝等相关知识
#include<iostream>
using namespace std;
class person
{
public:
//构造一个函数;
person()
{
cout << "无参构造函数调用!" << endl;
}
//构造一个有参函数
person(int a)
{
p_age = a;
cout << "有参构造函数调用" << endl;
}
//构造一个拷贝构造函数;
person(const person&p)
{
p_age = p.p_age;
cout << "拷贝构造函数调用!" << endl;
}
//构造析构函数;
~person()
{
cout << "析构函数调用调用!" << endl;
}
int p_age;
};
//*--------使用一个已经创建完毕的对象来初始化一个新对象---------//
void test01()
{
//如果不写拷贝构造,编译器会自动添加拷贝构造,并且做浅拷贝操作
person p1(2);
person p2(p1);
cout << "p2的年龄为: " << p2.p_age << endl;
}
void test02()
{
//如果用户提供有参构造,编译器不会提供默认构造,会提供拷贝构造
person p1; //此时如果用户自己没有提供默认构造,会出错
person p2(10); //用户提供的有参
person p3(p2); //此时如果用户没有提供拷贝构造,编译器会提供
//如果用户提供拷贝构造,编译器不会提供其他构造函数
person p4; //此时如果用户自己没有提供默认构造,会出错
person p5(10); //此时如果用户自己没有提供有参,会出错
person p6(p5); //用户自己提供拷贝构造
}
int main()
{
test01();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
//先定义一个类;
class person
{
public:
//1. 构造函数,没有返回值也不写void
person()
{
cout << "构造函数,没有返回值也不写void" << endl;
}
person(int a,int height)
{
p_age = a;
p_height = new int(height); //堆区的数据由程序员手动开辟数据
cout << "有参构造函数调用" << endl;
}
//自己实现拷贝构造函数;
person(const person&p)
{
p_age = p.p_age;
//深拷贝操作;
//p_height = p.p_height; 编译器默认实现的就是这行代码;
p_height = new int(*p.p_height);
}
//2. 析构函数
//对象早在销毁前,会自动调用析构函数,而且只能调用一次;
~person()
{
//析构代码,将堆区开辟的数据做释放操作;
if (p_height != NULL)
{
delete p_height;
}
cout << "构造函数,没有返回值也不写void" << endl;
}
int p_age;
int *p_height;
};
void test01()
{
person p1(10,180);
cout << "p1的年龄为:" <<p1.p_age<<endl<<"p1的身高为:"<<*p1.p_height<< endl;
person p2(p1);
cout << "p1的年龄为:" << p2.p_age << endl << "p1的身高为:" << *p2.p_height << endl;
}
int main()
{
test01();
//person p;
system("pause");
return 0;
}
/*
程序输出:
有参构造函数调用
p1的年龄为:10
p1的身高为:180
p1的年龄为:10
p1的身高为:180
构造函数,没有返回值也不写void
构造函数,没有返回值也不写void
*/
计划再下周结束前完成146课之前的内容。
2:英语方面学习相对较少,只背诵了两天单词。。。
3:周末也会接着学习,加强锻炼。坐等开学通知