【问题标题】:operator overloading - inline non-member functions运算符重载 - 内联非成员函数
【发布时间】:2013-11-29 15:22:21
【问题描述】:

好的,这样我就可以让我的代码工作了,但是有些事情困扰着我。它与运算符重载和使非成员函数内联有关。这是一个实现复数对象的非常简单的程序:

包含在 Complex.h 中

using namespace std;

class Complex {
 private:
  double real;
  double imaginary;

 public:

  Complex(void);
  Complex(double r, double i);
  double getReal();
  double getImaginary();
  string toString();
};

inline Complex operator+(Complex lhs, Complex rhs);

...在 Complex.cc 中

#include <sstream>
#include <string>
#include "Complex.h"

using namespace std;

Complex::Complex(void)
{
...not important...
}

Complex::Complex(double r, double i)
{
  real = r;
  imaginary = i;
}

double Complex::getReal()
{
  return real;
}

double Complex::getImaginary()
{
  return imaginary;
}

string Complex::toString()
{
...what you would expect, not important here...
}


inline Complex operator+(Complex lhs, Complex rhs)
{
  double result_real = lhs.getReal() + rhs.getReal();
  double result_imaginary = lhs.getImaginary() + rhs.getImaginary();

  Complex result(result_real, result_imaginary);

  return(result);
}

最后在 plus_overload_test.cc 中

using namespace std;

#include <iostream>
#include "Complex.h"

int main(void)
{
  Complex c1(1.0,3.0);
  Complex c2(2.5,-5.2);

  Complex c3 = c1 + c2;

  cout << "c3 is " << c3.toString() << endl;

  return(0);
}

使用执行链接的 makefile 使用 g++ 编译会产生错误:

plus_overload_test.cc:(.text+0x5a): undefined reference to `operator+(Complex, Complex)'

如果我只是从 Complex.h 和 Complex.cc 中的 operator+ 之前删除“内联”,那么一切都会编译并按应有的方式工作。为什么 inline 修饰符会导致此错误?每个人,例如:

Operator overloading

http://en.cppreference.com/w/cpp/language/operators

似乎建议为了重载二元运算符,函数应该是非成员和内联的。那么为什么我将它们内联时会遇到错误?

而且,是的,我意识到 inline 修饰符可能是一个红鲱鱼,因为现代编译器应该注意这一点。但我仍然很好奇。

干杯!

【问题讨论】:

    标签: c++ overloading inline operator-keyword non-member-functions


    【解决方案1】:

    inline 函数必须在每个使用它的文件中定义。

    如果您想要标准中的准确措辞(第 7.1.2/4 节):

    内联函数应在使用它的每个翻译单元中定义,并且在每种情况下都应具有完全相同的定义。

    将其标记为 inline,但仅在一个翻译单元中定义,因此您与编译器的合同不符(可以这么说)。

    【讨论】:

    • 万岁,这行得通!我已经接受了你的回答。我没有足够的声誉来支持它。在我看来,这使得 inline 没有我希望的那么有用,因为它从根本上减少了封装。所以我想我会把它留给我的编译器来做出关于内联事物的所有决定。非常感谢!
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    相关资源
    最近更新 更多