栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++学习 2.13

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++学习 2.13

1、拷贝构造函数

三种时机:

1)使用一个已经创建完毕的对象来初始化一个新对象

2)值传递的方式给函数参数传值

3)以值方式返回局部对象

注意拷贝构造函数形参参数的写法

Person(const Person &p)
{    
    cout<<"Person拷贝构造函数调用"< 
2、构造函数使用规则 

1)默认构造函数(无参,函数体为空)

2)默认析构函数(无参,函数体为空)

3)默认拷贝构造函数,对属性进行值拷贝

如果写了有参构造函数,编译器不再提供默认构造。(自己写的高级构造函数会屏蔽编译器提供的低级构造函数)

3、深拷贝和浅拷贝

浅拷贝:简单的赋值拷贝操作

深拷贝:在堆区重新申请空间,进行拷贝操作(需要手动释放,delete)

#include
using namespace std;
class Person{
public:
    Person()
    {
        cout << "Person默认构造函数调用" << endl;
    }
    Person(int age, int height)
    {
    m_Age = age;m_Height = new int(height);//在堆区创建一个值为height的变量,需要在析构函数中手动释放
    }
    ~Person()
    {
        if (m_Height != NULL)
            {
                delete m_Height;m_Height = NULL;
            }
        cout << "Person析构函数调用" << endl;
    }
    Person(const Person& p)
    {
        m_Age = p.m_Age;
        //m_Height=p.m_Height;//浅拷贝,编译器实现的代码
        m_Height = new int(*p.m_Height);//深拷贝,在堆区创建一个内存存储变量
        cout << "Person拷贝构造函数调用" << endl;
    }
    int m_Age;int* m_Height;//堆区变量,需要手动释放
};
void test01()
{
    Person p1(18, 170);
    Person p2(p1);
    cout << "p1的年龄:" << p1.m_Age << " 身高:" << *p1.m_Height << endl;
    cout << "p2的年龄:" << p2.m_Age << " 身高:" << *p2.m_Height << endl;
}
int main()
{
    test01();
    system("pause");
    return 0;
}
4、初始化列表

作用: c++提供了初始化列表语法,用来初始化属性

语法:构造函数():属性1(值1),属性2(值2)...{}

class Person
{
public://传统初始化
    Person(int a, int b, int c)
    {
    m_A = a;m_B = b;m_C = c;
    }//初始化列表初始化属性
    Person(int a,int b,int c) :m_A(a), m_B(b), m_C(c)
    {//更简化
    }
    int m_A;
    int m_B;
    int m_C;
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号