构造函数:
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;
}