有谁知道为什么它不能编译以及如何纠正它?我正在尝试使用朋友和模板。我正在使用Stroustrup C ++ 4th Ed Page 682-683中的这段代码。
谢谢
#include <iostream>
using namespace std;
template<typename T>
class Matrix;
template<typename T>
class Vector
{
T v[4];
public:
friend Vector operator*<>(const Matrix<T>&, const Vector&);
};
template<typename T>
class Matrix
{
Vector<T> v[4];
public:
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
};
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
Vector<T> r;
}
int main(int argc, char *argv[])
{
}
汇编:
clang++ -std=c++11 -pedantic -Wall -g test165.cc && ./a.out
test165.cc:12:19: error: friends can only be classes or functions
friend Vector operator*<>(const Matrix<T>&, const Vector&);
^
test165.cc:12:28: error: expected ';' at end of declaration list
friend Vector operator*<>(const Matrix<T>&, const Vector&);
^
;
test165.cc:19:22: error: friends can only be classes or functions
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
^
test165.cc:19:31: error: expected ';' at end of declaration list
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
^
朋友声明引用模板的实例operator*
(即operator*<T>
),但是模板不存在(尚未声明),然后导致错误。
您需要提前声明操作员模板。
例如
template<typename T>
class Matrix;
template<typename T>
class Vector;
// declaration
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v);
template<typename T>
class Vector
{
T v[4];
public:
friend Vector operator*<>(const Matrix<T>&, const Vector&);
};
template<typename T>
class Matrix
{
Vector<T> v[4];
public:
friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
};
// definition
template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
Vector<T> r;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句