繁体   English   中英

“C ++编程语言”部分“23.4.7朋友”中的错误

[英]Error in “The C++ Programming Language” Section “23.4.7 Friends”

我一直试图从“The C ++ Programming Language(4th Edition)”一节“23.4.7 Friends”中获得以下代码,但是无法成功。

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函数的名称后面的<>来表明朋友是模板函数。

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

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

函数模板必须已经在该点可见,否则无法实例化以产生您尝试成为朋友的重载

因此,将运算符定义移到Vector上面(这本身就要求我们提供前向声明) 解决了这个问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM