【问题标题】:friend operator confusion朋友运算符混淆
【发布时间】:2014-04-11 09:04:53
【问题描述】:

我是使用 .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)

但到目前为止,我更改格式的尝试都没有奏效。有什么建议吗?

【问题讨论】:

  • 错误是什么? operator+ 是在出现在友元声明之前声明的吗?
  • 第一个参数的类型不同。为什么在实现中是双倍的?
  • 嗨,你能再贴一些代码吗?您给我们的印象是,您有同一个运算符的两个重载;一个添加两个Matrix 元素,另一个添加一个double 标量到Matrix。但光是你的问题,是不可能帮到你的!
  • 您是否努力检查过任何 c++ 文档? msdn.microsoft.com/en-us/library/465sdshe.aspx

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


【解决方案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
    }
};

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如果我在实现中使用friend(.cpp 文件)。对吗?
    • 没有。所有“社交”事物——朋友、其他模块的函数声明和其他事物必须仅在头文件中声明。想象一下,您正在编写另一个开发人员正在使用的库。他将可以访问标题,但不能访问 [已编译] 库。是的,他想在他的模块中查看所有声明的项目(包括朋友)。
    • 我的意思是,我在.h.cpp 文件中都写了friend,对吗?
    • 不,这是不对的。你应该只在.h 中写friend。够了。
    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多