c++构造函数的定义


前言

构造函数的定义方式以及拷贝构造函数


一、构造函数

#include <iostream>
using namespace std;
class student
{
    public:
    int ag;
    string nam;
    student(int age, string name)
    {
        ag=age;
        nam=name;
    }
};//没加分号,记录丢人瞬间

以上是在类的内部以及构造函数内部初始化student类的对象的一些成员变量

#include <iostream>
#include <string>
using namespace std;
class student
{
    public:
    int ag;
    int  nam;
    student(int age, int  name);
};

student::student(int age, int name):ag(age),nam(name)
{
    cout << "构造函数的参数化列表" << endl;
}

以上是构造函数在类的外部定义以及使用参数化列表的形式给创建的对象的一些成员变量赋值


二、拷贝构造函数

什么时候会用到拷贝构造函数呢?当我们用一个对象给另外一个对象进行赋值的时候。
此时拷贝构造函数分为两种类型:一种是浅拷贝,另一种是深拷贝
如果我们不声明拷贝构造函数,那么编译器自己执行的拷贝构造函数是浅拷贝,但是浅拷贝只适用于类中没有动态数据成员的情况,当类里面有动态数据成员时就要使用深度拷贝。

#include<iostream>
using namespace std;
class A
{
    public:
        int a;
        A(int b)
        {
            a = b;
            cout << "有参构造" << endl;
        }
        A()
        {
            cout<<"无参构造"<<endl;
        }
        A(const A &B)
        {
            a = B.a;
            cout<< "拷贝" << endl;
        }
        void fun()
        {
            int x;  
        }
};
void test()
{
    A x;//无参构造不能使用括号,会被编译器认为是函数声明
    A y(2);//括号调用有参构造
    A z(y);//括号调用拷贝构造函数
}
int main()
{
    test();
    return 0;
}

总结

定义类的时候最后没加分号,编译器疯狂报错,“丢人”

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值