Home  >  Article  >  Backend Development  >  Why Does Operator Overloading in a Header File Lead to Multiple Definition Errors?

Why Does Operator Overloading in a Header File Lead to Multiple Definition Errors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 05:06:02757browse

Why Does Operator Overloading in a Header File Lead to Multiple Definition Errors?

Multiple Definition of Operator Overload in Header File

In the provided code example, the compiler encounters a multiple definition error for the operator<< overload for the Complex class. Despite protecting the header file with preprocessor guards, this error arises due to the definition of the operator<< function being placed within the header.

Specifically, the line std::ostream& operator<<(std::ostream& o, const Complex& Cplx) in the header file is not a declaration, but rather a definition. As a result, when both complex.cpp and main.cpp include the header file, the compiler detects duplicate definitions of the operator<< function during linking.

Unlike the real() member function, which is implicitly inlined and therefore not susceptible to multiple definition errors, the operator<< overload is explicitly defined in the header file. Therefore, it must be explicitly marked as inline using the inline keyword to allow for multiple definitions.

inline std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
    return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}

Alternatively, the definition of the operator<< overload can be moved to the complex.cpp source file to prevent the multiple definition error. By separating the declaration and definition, the compiler can correctly handle the reference to the operator<< function in main.cpp without encountering multiple definitions.

The above is the detailed content of Why Does Operator Overloading in a Header File Lead to Multiple Definition Errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn