对象的初始化和清理
#include<iostream>
using namespace std;
//构造函数的调用规则
//1.创建一个类,c++编译器会给每个类添加至少3个函数
//默认构造(空实现)
//拷贝构造(值拷贝)
//2.
//如果我们写了有参构造函数,编译器就不在提供默认构造,依然提供拷贝构造
//如果我们写了拷贝构造函数,编译器就不再提供其他普通构造函数了
class Person {
public:
/*Person()
{
cout << "Person默认构造函数" << endl;
}*/
Person(int a)
{
age = a;
cout << "Person含参构造函数" << endl;
}
/*Person(const Person & p)
{
age = p.age;
cout << "Person拷贝构造函数" << endl;
}*/
~Person()
{
cout << "Person析构构造函数" << endl;
}
int age;
};
//void test1() {
// Person p;
// p.age = 18;
// Person p2(p);
// cout << "p2年龄为" << p2.age << endl;
//
//}
void test2()
{
Person p(10);
Person p2(p);
cout << "p2年龄为" << p2.age << endl;
}
int main() {
//test1();
test2();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
class Person {
public:
Person() {
cout << "Person默认构造函数" << endl;
}
Person(int a, int h) {
age = a;
hight = new int(h);
cout << "Person含参构造函数" << endl;
}
Person(const Person &p)
{
//自己实现拷贝函数,解决浅拷贝带来问题
age = p.age;
//hight = p.hight; //浅拷贝,默认的
hight = new int(*p.hight); // *解引用
cout << "Person拷贝构造函数" << endl;
}
~Person() {
if (hight != NULL)
{
//析构代码,将堆区开辟数据释放
delete hight;
hight = NULL; //防止野指针
}
cout << "Person析构构造函数" << endl;
}
int age;
int * hight;
};
void test()
{
Person p1(19, 160);
Person p2(p1);
cout << "p2年龄为" << p2.age <<"身高"<<*p2.hight<< endl; //不*输出是指针,带*解引用
Person p3(20, 190);
Person p4(p3);
cout << "p4年龄为" << p4.age << "身高" << *p4.hight << endl;
}
int main() {
test();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
class Person {
public:
//传统初始化列表
/*Person(int m_a, int m_b, int m_c)
{
a = m_a;
b = m_b;
c = m_c;
}*/
//初始化列表,初始化属性
Person(int m_a, int m_b, int m_c) :a(m_a), b(m_b), c(m_c)
{
}
int a;
int b;
int c;
};
void test()
{
Person p(20, 40, 70);
cout << "a=" << p.a << ",b=" << p.b << ",c=" << p.c << endl;
}
int main() {
test();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
class Phone {
public:
Phone(string p)
{
phone_name = p;
cout << "Phone的构造函数调用" << endl;
}
~Phone()
{
cout << "Phone的析构函数调用" << endl;
}
string phone_name;
};
class Person
{
public:
//相当于Phone phone = p 隐式转换法
Person(string n, string p):name(n), phone(p)
{
cout << "Person的构造函数调用" << endl;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
string name;
Phone phone;
};
//注:当其他类对象作为本类成员,构造时候先构造类对象,再构造自身.析构的顺序与构造相反
void test()
{
Person p("张三", "小米100");
cout << "名字:" << p.name << ",使用手机:" << p.phone.phone_name << endl;
}
int main() {
test();
system("pause");
return 0;
}
评论列表 (0 条评论)