C++(OOP)类定义详解(2)

类里面可以 - 定义成员函数
类里面可以 - 使用别名简化

#include <iostream>
#include <string>

using namespace std;

/* 定义一个Screen类 */
class Screen{
public:
	/* 类中可以使用别名 作用域是整个类 */
	typedef std::string::size_type index;
	Screen (index ht = 0, index wd = 0):contents(ht * wd, 'A'),cursor(0),height(ht),width(wd){}  // 构造函数
	/*  写在类内部的函数都是内联函数 */
	/*  类中也是可以定义重载函数的  具体定义了什么函数不需要关心,只是个演示 */
	char get() const { return contents[cursor];}
	char get(index r, index c) const 
	{
		index row = r * width;
		return contents[row + c];
	}
private:
	/* 具体定义了什么私有成员不需要关心,只是个演示  */
	std::string contents; 
	index cursor;
	index height, width;
}; // ";" 很重要
int main()
{
	Screan a(10, 100);
	cout << "test" << endl;
	return 0;
}

类中内联成员函数的3种定义方法

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
	Person(const int &ag, const std::string &nm, const std::string &add):age(ag),name(nm),address(add){};
	/* 第一种类内联定义方法 在类内直接定义 */
	int getAge() const { return age; };
	/* 第二种类内联定义方法 在类内声明函数 在外边定义inline函数 */
	std::string getName() const;
	/* 第三种类内联定义方法 在类内声明inline函数 在外边定义函数  */
	inline std::string getAddress() const;
private:
	int age;
	std::string name;
	std::string address;
};
/* 第二种类内联定义方法 在类内声明函数 在外边定义inline函数 */
inline std::string Person::getName() const { return name; }
/* 第三种类内联定义方法 在类内声明inline函数 在外边定义函数 */
string Person::getAddress() const { return address; }

int main()
{
	Person a(15, "John", "shanghai");
	cout << a.getName() << " " << a.getAge() << " " << a.getAddress() << endl;
	cout << "test" << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值