C++(OOP)构造函数

设计一个类的时候必须写上一个构造函数

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
	/* 设计一个类的时候必须写上一个构造函数 */
	Person(const std::string &nm, int a):name(nm),age(a){}
private:
	std::string name;
	int age;
};

int main()
{
	Person a("John", 22);
	return 0;
}
#include <iostream>
#include <string>

using namespace std;

class Sales_item
{
public:
	/* 构造函数和类名相同 */
	/* 构造函数没有返回类型 */
	/* 构造函数可以初始化成员 */
	/* 构造函数可以重载 */
	/* 构造函数不要用 const */
	Sales_item(const std::string &book):isbn(book),units_sold(0),revenue(0.0){}
	Sales_item():units_sold(0),revenue(0.0){}
	Sales_item(int units, double price){
		this->units_sold = units;
		this->revenue = units * price;
	}
private:
	std::string isbn;
	unsigned units_sold;
	double revenue;
};

int main()
{
	Sales_item item1;	
	Sales_item item2("0-201-82470-1");	
	Sales_item *p = new Sales_item();
	delete p;

	cout << "test" << endl;
	return 0;
}

构造函数 初始化列表

#include <iostream>
#include <string>

using namespace std;

class Sales_item
{
public:
	// 方法1 直接赋值 速度慢 不推荐
//	Sales_item(const std::string &book, int units, double amount){
//		this->isbn = book;
//		this->units_sold = units;
//		this->revenue = amount;
//	}
	// 方法2 初始化列表 速度开 推荐
	Sales_item(const std::string &book, int units, double amount):isbn(book),units_sold(units),revenue(amount){}
private:
	std::string isbn;
	unsigned units_sold;
	double revenue;
};

int main()
{
	cout << "test" << endl;
	return 0;
}
#include <iostream>

using namespace std;

class Dog
{
public:
	/* const 数据成员只能用初始化列表 */
	/* 引用类型 数据成员只能用初始化列表 */
	/* 没有默认构造函数的类类型 数据成员只能用初始化列表 */
	Dog():legs(4){};
private:
	/* 列表初始化顺序 是定义数据成员的顺序 */
	/* 初始化列表中没有写数据成员 C++会默认初始化  */
	std::string name;  // 顺序 1
	const int legs;  // 顺序 2
};

int main()
{
	Dog a;
	cout << "test" << endl;		
	return 0;
}

explicit关键字使用
有时使用构造函数,会发生隐式创建,为了避免这种情况需要使用explicit关键字

class Sales_item
{
public:
	explicit Sales_item(const std::string &book):isbn(book),units_sold(0),revenue(0.0){}
	explicit Sales_item():units_sold(0),revenue(0.0){}
	explicit Sales_item(int units, double price){
		this->units_sold = units;
		this->revenue = units * price;
	}
private:
	std::string isbn;
	unsigned units_sold;
	double revenue;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值