类的各种成员函数及区别


前言

C++中,成员函数可以分为普通成员函数、静态成员函数和const成员函数


一、各种成员函数

class Date
{
public:
	Date(int year, int month, int day)
		: year_(year)
		, month_(month)
		, day_(day)
	{
	}
	void show() const
	{
		cout << "year:" << year_ << " month:" << month_ << " day:" << day_ << " ";
	}
private:
	int year_;
	int month_;
	int day_;
};

/*

	继承:a kind of,一种
	组合:a part of,一部分
	商品日期更像是商品的一部分,应该用组合的方式

*/

class Goods
{
public:
	Goods(int id, string name, int price, int year, int month, int day)
		: date_(year, month, day)
		, id_(id)
		, name_(name)
		, price_(price)
	{
		count_++;
	}
	void show()	const 	
	{
		date_.show();
		cout << "id:" << id_ << " name:" << name_ << " price:" << price_ << endl;
	}
	static int getCount()		//静态成员函数
	{
		return count_;
	}
private:
	Date date_;
	int id_;
	string name_;
	int price_;
	static int count_;		//静态成员变量的声明
};
int Goods::count_ = 0;		//静态成员变量的初始化

1、静态成员变量

静态成员变量在类内声明,在类外定义初始化
静态成员变量可以用类引用,也可以通过对象引用

2、静态成员函数

静态成员函数不能使用普通成员变量,能使用静态成员变量
静态成员函数可以通过类调用,也可以通过对象调用

3、const成员函数

一般将不修改成员变量的成员函数用const修饰,因为const对象只能调用const成员函数
const成员函数既能够被普通对象调用,也能被const对象调用


总结

静态成员函数里只能使用静态成员变量
const成员函数不能修改成员变量,普通对象和const对象都能调用const函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值