c++中重载运算符何时通过引用传递

When to pass by reference for overloading operators in c++?

本文关键字:引用 何时通 重载 运算符 c++      更新时间:2023-10-16

我已经实现了一个自定义指针类,让我们称之为japan。这是一个声明和定义,以及我正在尝试使用的一个主要函数。

class japan
{
public:
japan(T *ptr) : ptr(ptr)
{}
T *get()
{
return this->ptr;
}
bool operator==(const T *&other)
{
return ( this->get() == other );
}
friend bool operator==(const T *&l, japan<T> r)
{
return ( r == l );
}
private:
T *ptr;
};
int main(void)
{
int j;
int *k =  & j;
japan<int> nihon(k);
if(k == nihon)
if(nihon == k)
std::cout << "yayn";
if(nihon == NULL)
return 1;
else
return 0;
if(NULL == nihon)
return 5;
}

当实际T*传入时,我的==运算符似乎在实际T*上工作得很好,但是如果我用NULL调用它,我的编译器会产生错误:

stuff.cpp:40:15: error: no match for 'operator==' in '0l == nihon'
stuff.cpp:40:15: note: candidate is:
stuff.cpp:21:16: note: bool operator==(const int*&, japan<int>)
stuff.cpp:21:16: note:   no known conversion for argument 1 from 'long int' to 'const int*&'

据我所知。。。应该有某种形式的从T*到long int的转换,否则NULL的赋值运算符将不起作用。然后我对我的操作员进行了一点修改。

这两个功能都能在中工作

friend bool operator==(T *l, japan<T> r);
friend bool operator==(const T *l, japan<T> r);

然而,这一次失败了。

friend bool operator==(const T *&l, japan<T> r);

这让我觉得,改变NULL会改变一个从未使用过的值,但它是一个常量引用。。。那么,为什么会失败呢。在c++中,不在布尔运算符上使用引用是常见的吗?我看到的大多数例子总是使用引用,但这似乎只适用于lvalues。。。那么,在重载时传递值是更好的做法吗?

还有:

为什么我会收到警告:

warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
ptr.h:106:9: note: candidate 1: bool japan<T>::operator==(const T* const&) const [with T = Geometry]
stuff.cpp:239:15: note: candidate 2: operator==(int, long int) <built-in>

当使用==时,我的japan类是否以某种方式暴露了它的T,我问这个问题是因为我在我正在处理的没有定义==运算符的东西中发现了这个类(尽管它在很多地方都被使用),我添加了一个。。。却发现问题没完没了。

在C++中,0是一个被滥用的整数。它用于将0反映为int类型的值,也用于表示null指针。

你们的类型根本不同。没有常量正确性问题,只是NULL是0的宏,这与泛型编程不太配合。你可以试试

static_cast<T*>(NULL); 

当与null指针进行比较时,或者更好地使用nullptr,这是新标准希望您在表示"null指针"时使用的