Type: Note
測試 C++ 的 & 與 const
雖然 先宣告個class, 但請從main function 看起吧
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
class Vec2D {
public:
Vec2D() :
x(0), y(0) {
}
Vec2D(int x, int y) :
x(x), y(y) {
}
public:
int mht_dist() const { // const代表此function不可以修改Data Member
//this->x++; // Compiler Error! x為Data Member,因此不可以修改
return this->x + this->y;
}
void func1(const Vec2D &v) {
//v.x++; // Compiler Error! parameter 宣告成 const, 不能被修改
//常配合 '&' 出現, 表示 我不會動你的物件, 安心傳給我
//若不加 '&', 表示 call by value, 加了 const 好像就有點多餘
printf("%p, %p\n", this, &v);
}
void func2(Vec2D &v) {
}
Vec2D& func3() {
//會回傳物件, 而不會copy, 這有點trick, 可以請教google
return *this;
}
const Vec2D func4() {
//不知道 return 加上 const 有什麼意義...
//即使不能修改 return 值, 好像也沒什麼差別
return *this;
}
public:
int x, y;
};
測試
int main(int argc, const char **argv) {
Vec2D vec = Vec2D(1, 2);
vec.func1(vec);
vec.func1(Vec2D(3, 4));
//vec.func2(Vec2D(3, 4)); //沒有const, 又用 '&' 是無法用這種方式傳進去
vec.func2(vec); //必須有變數
printf("%p, %p\n", &vec, &vec.func3()); //收到的指標跟原來的物件相同
return 0;
}
沒有留言:
張貼留言