运算符内联非成员函数

operator inline non-member functions

本文关键字:成员 函数 运算符      更新时间:2023-10-16

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

包含在 复杂.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);
}

使用执行链接的生成文件使用 g++ 进行编译会产生错误:

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

如果我只是从 Complex.h 中的运算符 + 之前删除"内联"并 Complex.cc 那么一切都会编译并正常工作。 为什么内联修饰符会导致此错误? 每个人,例如:

运算符重载

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

似乎建议对于重载二进制运算符,函数应该是非成员和内联的。 那么,为什么我在内联时会遇到错误呢?

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

干杯!

必须在

使用inline函数的每个文件中定义该函数。

如果您需要标准 (§7.1.2/4) 中的精确措辞:

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

它标记为inline,但只在一个翻译单元中定义,你没有满足你与编译器的合同(可以这么说)。