C++ 构造函数

构造函数:

C++ 构造函数是指 函数名与类型相同的函数.切不返回任何类型也不会返回void

构造函数的作用:

构造函数一般用于为某些成员变量设置初始值

构造函数可以带参数也可以不带参数,

无参构造函数

#include <iostream>
#include <string>
using namespace std;

class Fun_a
{
public:
    int a;
    int b;
    //无参构造函数
    Fun_a()
    {
        a = 3;
        b = 7;
    };
    void getAdd()
    {
        cout << a + b << endl;
    }
};
 
int main()
{
    Fun_a a;
    a.getAdd();
    return 0;
}

或者,可以外部定义使用域运算符"::",如下

#include <iostream>
#include <string>
using namespace std;

class Fun_a
{
public:
    int a;
    int b;
    Fun_a(); //无参构造函数
    void getAdd();
};

Fun_a::Fun_a()
{
    a = 3;
    b = 7;
};

void Fun_a::getAdd()
{
    cout << a + b << endl;
}

int main()
{
    Fun_a a;
    a.getAdd();

    return 0;
}

有参的构造函数

#include <iostream>
#include <string>
using namespace std;

class Fun_a
{
public:
    Fun_a(int a, int b); //有参构造函数
};

Fun_a::Fun_a(int a,int b){
   cout<<a+b<<endl;
}
 

int main()
{
    Fun_a fun_a(3, 7);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值