类
class Book {
private:
string title, author;
public:
Book(String t, String a){
title = t;
author = a;
}
string toString(){
return title + " " + author;
}
};
只读方法
- 方法名末尾加上
const
关键字后, 方法不可以更改任何参数的值
string getTitle const {
return title;
}
Struct
struct FBullCowCount
{
int32 Bulls = 0;
int32 Cows = 0;
}
在方法里面使用
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
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;
}
Book &operator++(int) {
Book b = *this;
++*this;
return b;
}
header files
- 不可以使用
using namespace std;