Issue
I want to overload the operator +=
in the class of Complex
, but I get this error when I compile this project by g++ main.cpp complex.cpp -I complex.hpp -o out
:
Undefined symbols for architecture x86_64:
"Complex::operator+=(Complex const&)", referenced from:
_main in main-bee8d4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Project
project tree
.
├── complex.cpp
├── complex.hpp
└── main.cpp
complex.hpp
#ifndef __COMPLEX__
#define __COMPLEX__
class Complex
{
public:
Complex(double x=0, double y=0):re(x), im(y){};
double real() const {return re;}
double imag() const {return im;}
Complex& operator+=(const Complex& res);
private:
double re,im;
};
#endif
complex.cpp
#include "complex.hpp"
inline Complex&
Complex::operator+=(const Complex& res)
{
this->re += res.re;
this->im += res.re;
return *this;
};
main.cpp
#include "complex.hpp"
#include <iostream>
int main()
{
Complex c1(1, 1);
Complex c2(3, 4);
c2 += c1;
std::cout << "real part:" << c2.real() << ", "
<< "image part:" << c2.imag() << std::endl;
return 0;
}
g++
$g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin