游戏编程笔记4 --- OOP

  • 定义写在 header file 里面
    • 必须以;结尾
class Book {
	private:
	string title, author;

	public:
	Book(String t, String a){
		title = t;
		author = a;
	}
	
	string toString(){
		return title + " " + author;
	}
};
  • 方法的具体实现写在 cpp 文件里面

只读方法

  • 方法名末尾加上const关键字后, 方法不可以更改任何参数的值
string getTitle const {
	return title;
}

Struct

  • header file:
struct FBullCowCount
{
	int32 Bulls = 0;
	int32 Cows = 0;
}
  • cpp file:
在方法里面使用
FBullCowCount BCCount;
BCCount.Bulls++;
BCCount.Cows++;

Operators

Accessor Operator ->

//首先搞一个pointer
AActor* SomeActor;
//如何调用pointer指向的对象的方法呢? 两种方式:

//方法一: dereference the pointer
(*SomeActor).GetName();

//方法二: acessor operator
SomeActor -> GetName();

Operator Overloading

  • 如果有返回值, 则 operator 前面要加上 & --> &operator

Relational Operator

  • ==的重写
    • 如果放在类的外面: 则需要有两个参数
    • 如果放在类的里面: 则只需要有一个参数
//放在类的外面
bool operator==(const Book &b1, const Book &b2)  { //这里用reference是为了更高效
	return b1.title == b2.title;
}
//放在类的里面
bool operator==(const Book &b) {
	return title == b.title;
}
  • > >= < <= 的重写, 和 == 的是一样的

Input Output Operator

  • <<的重写
    • 要放在类的外面
ostream &operator<<(ostream &out, const Book &b) {
	return cout << b.title << " " << b.author << endl;
}
  • >>的重写
    • 要放在类的外面
istream &operator>>(istream &in, Book &b) {
	string title, author;
	cin >> title >> author;
	b = Book(title, author);
	return cin;
}

Arithmetic Operator

  • 要放在类的里面, public区域
  • += 的重写
Book &operator+=(int i) {
	page += i;
	return *this;
}
  • = 的重写
Book &operator=(const Book &b) {
	title = b.getTitle();
	author = b.getAuthor();
	return *this;
}
  • + - 的重写不需要返回 *this
  • ++ -- 的重写都需要返回 *this
  • ++x --x 的重写
Book &operator++() {
	page++;
	return *this;
}
  • x++ x-- 的重写
Book &operator++(int) {
	Book b = *this;
	++*this;
	return b;
}

header files

  • 不可以使用using namespace std;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值