我正在尝试将数组元素的值打印为cout << array[0]
,(其中数组是使用operator []的一些美化类),但C ++类型系统似乎令人难以置信。 GCC错误是这样的:
example.cpp:44:20: error: no match for ‘operator<<’ in ‘std::cout << a_0.fixedarr<T, N>::operator[] [with T = int, long unsigned int N = 5ul, size_t = long unsigned int](0ul)’
(整个来源都来自更复杂的东西,但我想我已经把它简化为一个最小的例子了。)
#include <assert.h>
#include <cassert>
#include <climits>
#include <cstdio>
#include <iostream>
using namespace std;
template<typename T>
class fixedarrRef{
T* ref;
int sz;
public:
fixedarrRef(T* t, int psz){ ref = t; sz = psz;}
T val(){ return ref[0]; }
};
template<typename T, size_t N>
class fixedarr{
public:
T arr[N];
fixedarr(){
for(int i=0; i<N; ++i){
arr[i] = 0;
}
}
inline fixedarrRef<T> operator[] (const size_t i) const{
assert ( i < N);
return fixedarrRef<T>((T*)&arr[i], N-i);
}
};
template <typename T>
ostream & operator << (ostream &out, fixedarrRef<T> &v)
{
return (out << v.val());
}
int main() {
fixedarr<int, 5> a_0;
fixedarrRef<int> r = a_0[0];
cout << (a_0[0]) << endl;
// cout << r << endl;
return 0;
}
请注意,最后注释的代码有效。提前谢谢。
答案 0 :(得分:3)
您应该在T fixedarrRef::val()
const 中声明fixedarrRef<T> &v
和operator <<
。
T val() const { return ref[0]; }
和
template <typename T>
ostream & operator << (ostream &out, const fixedarrRef<T> &v)
答案 1 :(得分:3)
a_0[0]
返回一个临时对象,该对象不能绑定到非const引用,因此operator <<
应将其参数作为const引用。
答案 2 :(得分:0)
您的[]
运算符返回fixedarrRef
类的实例,并且您正尝试在此实例上使用运算符<<
。
由于没有为<<
定义fixedarrRef
运算符,您将获得错误。
定义此运算符,它应该可以工作。