构造函数的简单实用
#include<iostream>
using namespace std;
class ctext
{
public:
int age;
float len;
ctext() // 构造函数,1用来初始化类的变量,2无返回值,3和类名一样,4在创建对象时调用
// ctext():age(12) ,f(120.12f) 也可以这么写 初始化列表的方式 会被赋值语句覆盖
{
age = 12;
len = 17.17f; // 以f结尾才算flout类型
}
};
int main()
{
ctext text;
cout << text.age << endl;
system("pause");
return 0;
}
构造函数的传参
#include<iostream>
using namespace std;
class ctext
{
public:
int age;
float len;
ctext(int a= 12, float b = 17.17) // 构造函数传参,里面可以设置默认值可以不设置,创建对象实体时需要传参
{
age = a;
len = b; // 以f结尾才算flout类型
}
};
int main()
{
ctext text1; //创建对象 使用默认值
ctext *text2 = new ctext(13, 18.18); // 创建堆栈对象,使用传参的方式
cout << text1.age << endl;
cout << text2->age << endl;
system("pause");
return 0;
}