qaz*_*wsx 0 c++ pointers 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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码有效.但在我看来 b->isSelf(a)应该真的是b -> isSelf(&a)因为isSelf期望一个类型的地址C?!
[编辑]其他问题:
1)有没有办法isSelf使用pass by value 实现这个功能?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;
}
Run Code Online (Sandbox Code Playgroud)
有以下区别:
bool C::isSelf (C& param) // pass by 'reference'
^^^
Run Code Online (Sandbox Code Playgroud)
和
bool C::isSelf (C* param) // pass by 'address'
^^^
Run Code Online (Sandbox Code Playgroud)
所以在第二版本中,C对象(即C*)的地址是预期的而不是第一版.
另请注意,内部第1版和第2版可能类似地实现; 但是有一个语法差异.有第3版:
bool C::isSelf (C param) // pass by value
^^^
Run Code Online (Sandbox Code Playgroud)
编辑问题:
1)有没有办法
isSelf()使用pass by value 实现这个功能?
不符合您的要求.因为它创建了一个永远不会匹配的新值.从代码中删除值版本的传递.
除此之外,对于任何函数,通常您应该选择按值传递或通过引用传递.你不能同时拥有它们,因为它们的函数调用语法都是相同的,这将导致歧义.
2)实现是否通过引用传递并通过指针传递正确?
它们是正确的,但您可以将它们简化为:
bool C::isSelf(const C &c) const // don't give postfix '1', simply overload
{ ^^^^^
return (&c == this);
}
bool C::isSelf(C* const c) const // don't give postfix '3', simply overload
{ ^^^^^
return (c == this);
}
Run Code Online (Sandbox Code Playgroud)
另外,请参阅执行此类操作的const correct-ness语法.
| 归档时间: |
|
| 查看次数: |
332 次 |
| 最近记录: |