【发布时间】:2009-09-06 08:40:15
【问题描述】:
在 C++ 中,传递 const 引用是一种常见的做法 - 例如:
#include <iostream>
using namespace std;
class X
{
public :
X() {m_x = 0; }
X(const int & x) {m_x = x; }
X(const X & other) { *this = other; }
X & operator = (const X & other) { m_x = other.m_x; return *this; }
void print() { cout << m_x << endl; }
private :
int m_x;
};
void main()
{
X x1(5);
X x2(4);
X x3(x2);
x2 = x1;
x1.print();
x2.print();
x3.print();
}
这个非常简单的示例说明了它是如何完成的 - 差不多。但是我注意到在 C# 中似乎并非如此。我必须在 C# 中传递 const 引用吗?我需要“ref”关键字做什么?请注意,我知道并理解 C# 引用和值类型是什么。
【问题讨论】:
-
由于您是在用 C++ 术语思考,因此将 ref 关键字视为指针的最佳方式可能是。如果将它与值类型一起使用,那么它是一个单指针,对于 ref 类型,它是一个指向指针的指针。
-
Eric Lipperts 博客是这类事情的一个很好的参考。特别是他的“参考不是地址”条目。 blogs.msdn.com/ericlippert/archive/2009/02/17/…
-
@MartinHarris 我已经阅读了Jon Skeet's blog post on the matter 并且找不到任何反对您评论的内容。感谢您指出相似之处。多亏了这条评论,我相信我已经更好地学习了 c++ 和 c# 中的概念。