<分区>
Possible Duplicate:
How to pass objects to functions in C++?
Operator & and * at function prototype in class
#include <iostream>
using namespace std;
class C {
public:
int isSelf (C& param);
};
bool C::isSelf (C& param)
{
if (¶m == this) return true;
else return false;
}
int main () {
C a;
C* b = &a;
cout << boolalpha << b->isSelf(a) << endl;
return 0;
}
此代码有效。但在我看来 b->isSelf(a)
应该是 b -> isSelf(&a)
因为 isSelf
需要一个地址输入 C
?!
[编辑] 附加问题:
1) 有没有一种方法可以使用按值传递来实现此 isSelf
函数?
2)引用传递和指针传递的实现是否正确?
bool C::isSelf1(const C &c)
{
if (&c == this) {
return true;
} else {
return false;
}
}
bool C::isSelf2(C c)
{
if (&c == this) {
return true;
} else {
return false;
}
}
bool C::isSelf3(C * c)
{
if (c == this) {
return true;
} else {
return false;
}
}
int main ()
{
C c1 (2);
C * c2 = &c1;
cout << boolalpha;
cout << c2 -> isSelf1(c1) << endl; // pass by reference
cout << c2 -> isSelf2(c1) << endl; // pass by value
cout << c2 -> isSelf3(&c1) << endl;// pass by pointer
return 0;
}