朋友操作员混淆

时间:2014-04-11 09:04:54

标签: c++ operator-overloading header-files friend

我是使用.h / .cpp文件的新手,我尝试将.cpp转换为.h和.cpp,我遇到了这个问题。这是错误的,我不知道如何解决它。在Primitives.h我有:

friend Matrix operator+(const Matrix&, const Matrix&);

在Primitives.cpp中我有:

    friend Matrix operator+ (const double b, const Matrix& a)

但到目前为止,我改变格式的尝试并没有奏效。有什么提示吗?

3 个答案:

答案 0 :(得分:1)

你应该这样做:

// header
class Matrix
{
public:
    friend Matrix operator+(const Matrix&, const Matrix&);
};

// source
Matrix operator+(const Matrix&, const Matrix&) { ... }

对于短操作符,直接在头文件中定义操作符可能更方便:

// header
class Matrix
{
public:
    friend Matrix operator+(const Matrix&, const Matrix&) {
        // code here
    }
};

答案 1 :(得分:0)

您不应在实施(friend文件)中使用.cpp。您应该仅在声明(仅在.h文件中)中使用它。

答案 2 :(得分:0)

试试这个

///your.h
class Matrix
{
    //your class
    friend Matrix operator+ (const double b, const Matrix& a);
};

////your.cpp
Matrix operator+ (const double b, const Matrix& a)
{
    //your code
    return yourobject;
}
相关问题