Can you please help me to know how I can avoid the error.. Thanks in advance.
file name: point.hh
#ifndef POINT_H
#define POINT_H
class Point{
private:
int x;
int y;
public:
Point();
};
#endif
file name:point.cc
开发者_C百科#include "point.hh"
#include <iostream>
using namespace std;
Point::Point()
{
x=0;
y=0;
cout<<"x="<<x;
cout<<"y="<<y;
}
file name: main.cc
#include"point.cc"
int main()
{
Point p; // calls our default constructor
}
You must include the header file, not the source file, in your main.cc
file to use the Point
class.
That is, replace:
#include"point.cc"
By:
#include"point.hh"
The rationale behind this is that a function definition, unless marked inline
, must respect the ODR ("One Definition Rule"). By including the source file in your other source file, you end up having two (identical) definitions of the Point::Point()
function in two different translation units.
When the linking process takes place, it sees this two definitions and complains: that is the error you get.
Another cause is the build command, if you have the same .cpp file listed twice you will definitely get this error and it will say that functions you didn't even write have the error.
Might help someone in the future.
精彩评论