运算符内联非成员函数
operator inline non-member functions
好的,所以我可以让我的代码工作,但有一些东西困扰着我。 它与运算符重载和使非成员函数内联有关。 这是一个非常简单的程序,它实现了一个复数对象:
包含在 复杂.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
,但只在一个翻译单元中定义,你没有满足你与编译器的合同(可以这么说)。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法