gpt4 book ai didi

c++ - 运算符重载 - 内联非成员函数

转载 作者:行者123 更新时间:2023-11-30 04:12:00 25 4
gpt4 key购买 nike

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

包含在 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+ 之前的“内联”,那么所有内容都会编译并正常工作。为什么内联修饰符会导致这个错误?每个人,例如:

Operator overloading

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

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

而且,是的,我意识到内联修饰符可能是一个转移注意力的问题,因为现代编译器应该处理这个问题。但我仍然很好奇。

干杯!

最佳答案

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

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

An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case.

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

关于c++ - 运算符重载 - 内联非成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20014536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com