【发布时间】:2012-02-03 00:36:46
【问题描述】:
可能重复:
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;
}
【问题讨论】: