C++基础知识(构造函数)

成员函数:构造函数,析构函数,常函数,拷贝函数,内联函数以及静态成员函数。

构造函数,自动调用,没有返回值。对象创建时调用。

#include<iostream>
using namespace std;

class CStu
{
public:
	int age;
	float f;
	//构造函数,自动调用
	CStu()//构造函数没有返回值
	{
		age = 12;
		f = 12.12f;
	}

	void fun()//初始化功能的函数
	{
		age = 12;
		f = 12.12f;
	}
};

int main()
{
	CStu stu;
	//stu.age = 13;
	//stu.fun();
	cout << stu.age << endl;
	system("pause");
	return 0;
}

作用:对数据成员进行赋值(初始化)。

有参数的构造函数

#include<iostream>
using namespace std;

class CStu
{
public:
	int age;
	float f;
	//构造函数,自动调用
	//CStu()//构造函数没有返回值
	//{
	//	age = 12;
	//	f = 12.12f;
	//}
	CStu(int a, float b=123.5f)
	{
		age = a;
		f = b;
	}
};

int main()
{
	CStu stu(3);//构造函数参数传递
	CStu *stu1 = new CStu(13, 13.4f);
	cout << stu.age << ' ' << stu.f << endl;
	cout << stu1->age << ' ' << stu1->f << endl;
	system("pause");
	return 0;
}

可以设置默认值

猜你喜欢

转载自blog.csdn.net/weixin_37753215/article/details/81636802