gpt4 book ai didi

c++ - 从 Stroustrup 的 C++ 编译模板 friend 示例的问题

转载 作者:行者123 更新时间:2023-12-01 14:47:26 24 4
gpt4 key购买 nike

有谁知道为什么这不会编译以及如何纠正它?我正在尝试使用 friend 和模板。我正在使用 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> ),但模板不存在(尚未声明),然后导致错误。
您需要提前声明运算符(operator)模板。
例如。

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;
}

关于c++ - 从 Stroustrup 的 C++ 编译模板 friend 示例的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62668815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com