Reputation: 13
I only declare the class once in a .hpp file and implement its member functions in another .cpp file. The .cpp and .hpp file in that order are below. I get the errors in the .cpp file. The first is on the 6th line saying 'multiple definition of complex::complex'and 'first defined here' This happens for every function, including the overloaded ctor. Am I unintentionally defining all these functions twice when I try to include their prototypes in the .hpp file?
I get no error as long as I include the .hpp file instead of the .cpp in the main file that I use the class in. How does this make any sense? How does the compiler access the .cpp file with all the function definitions?
#include <iomanip> // For fixed, setprecision()
#include <sstream> // For stringstream class
#include "Complex.hpp" // For the complex class declaration
complex::complex()
{
init(0,0);
}
complex::complex(double init_real, double init_imag)
{
init(init_real, init_imag);
}
double complex::get_imag()
{
return m_imag;
}
double complex::get_real()
{
return m_real;
}
//--------------------------------------------------------------------------------------------------
void complex::init(double init_real, double init_imag)
{
m_real = init_real;
m_imag = init_imag;
}
void complex::set_imag(double s)
{
m_imag = s;
}
-
void complex::set_real(double s)
{
m_real = s;
}
std::string complex::to_string()
{
std::stringstream sout;
sout << std::fixed << std::setprecision(4);
sout << "(" << get_real();
double imag = get_imag();
if (imag < 0) {
sout << " - " << -imag << 'i';
} else if (imag > 0) {
sout << " + " << imag << 'i';
}
sout << ")";
return sout.str();
}
#ifndef COMPLEX_HPP // See the comments in the header comment block regarding these two lines.
#define COMPLEX_HPP
#include <string> // Included because we are using the string class in to_string()
class complex
{
public:
complex();
complex(double , double);
double get_imag();
double get_real();
void set_imag(double);
void set_real(double);
std::string to_string();
private:
void init(double , double );
double m_real;
double m_imag;
};
#endif
The main file where these are used:
#include <fstream> // For ofstream class declaration
#include <iostream> // For cout, endl
#include "Complex.hpp" // So we can access the complex class declaration (hint: see Complex.cpp)
#include <string>
int main()
{
std::string filename; filename = "complex-test.txt";
std::ofstream...
.
.
.
return 0;
}
Upvotes: 1
Views: 269
Reputation: 1490
Including a cpp file is equivalent to importing the definition in that file. That means you have a definition in cpp file where it is actually defined and the definition silently gets into the file where you include. That way the linker generates 2 copies of definition for same function and gets confused. Compile should be fine but link would cause problems. Try avoiding cpp file inside #include
Upvotes: 2