【问题标题】:Error in "The C++ Programming Language" Section "23.4.7 Friends"“C++ 编程语言”部分“23.4.7 Friends”中的错误
【发布时间】:2014-02-01 21:01:36
【问题描述】:

我一直试图从“C++ 编程语言(第 4 版)”“23.4.7 朋友”一书中获得以下代码工作,但未能成功。

template<typename T> class Matrix;

template<typename T>
class Vector {
    T v[4];
public:
    friend Vector operator*<>(const Matrix<T>&, const Vector&); /* line 7 */
    // ...
};

template<typename T>
class Matrix {
    Vector<T> v[4];
public:
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&); /* line 14 */
    // ...
};

template<typename T>
Vector<T> operator*(const Matrix<T>& m, const Vector<T>& v)
{
    Vector<T> r;
    // ... m.v[i] and v.v[i] for direct access to elements ...
    return r;
}

以下是上述 API 的示例用法:

int main() {
    Matrix<int> lhs;
    Vector<int> rhs;
    Vector<int> r = lhs * rhs;

    return 0;
}

g++ 版本:

g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3

给出以下输出:

test.cpp:7: error: declaration of ‘operator*’ as non-function
test.cpp:7: error: expected ‘;’ before ‘<’ token
test.cpp:14: error: declaration of ‘operator*’ as non-function
test.cpp:14: error: expected ‘;’ before ‘<’ token

和版本:

Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

给出以下输出:

test2.cpp:7:19: error: friends can only be classes or functions
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
                  ^
test2.cpp:7:28: error: expected ';' at end of declaration list
    friend Vector operator*<>(const Matrix<T>&, const Vector&);
                           ^
                       ;
test2.cpp:14:22: error: friends can only be classes or functions
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
                     ^
test2.cpp:14:31: error: expected ';' at end of declaration list
    friend Vector<T> operator*<>(const Matrix&, const Vector<T>&);
                              ^
                              ;
4 errors generated.

书上说:

需要在firend函数名后面的明确 朋友是一个模板函数。

我无法在代码中发现问题,你可以吗?

【问题讨论】:

    标签: c++ templates operator-overloading friend


    【解决方案1】:

    是的,这是书中的一个错误。

    此时函数模板必须已经可见,否则it cannot be instantiated to produce the overload you're trying to befriend

    因此,将运算符定义移到 Vector 之上(这本身要求我们提供前向声明)solves the problem

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多