c++中重载运算符何时通过引用传递
When to pass by reference for overloading operators in c++?
我已经实现了一个自定义指针类,让我们称之为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指针"时使用的
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 如果非动态变量被指针引用,何时超出范围?
- 何时使用右值引用
- C++ 何时使用常量引用而不是转发引用
- 了解shared_ptr传入函数时引用计数何时递增
- C++ / Qt:如何检测主机名或IP地址何时引用当前系统?
- 常量引用函数参数的地址何时唯一?
- 返回的常量引用究竟何时被销毁
- 何时引用为右值引用
- 何时应存储指向函数的引用或指针?
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- 是否可以通过从lambda的引用中返回T型对象,而无需使用尾随返回类型语法
- 何时首选常量左值引用而不是右值引用模板
- c++中重载运算符何时通过引用传递
- 何时将类的引用分配给其父类的 instace
- 引用对象的动态类型何时可以更改
- 何时通过引用 C++ 中的函数来传递和返回
- 引用参数何时可以接受 int 文本
- 如果未在本机方法中创建,何时清除本地引用