ehd*_*hdv 1 c++ linker visual-studio visual-c++
我刚开始使用C++,也许有些东西我在这里做错了,但我很茫然.当我尝试构建解决方案时,我得到4个LNK2005错误,如下所示:
error LNK2005: "public: double __thiscall Point::GetX(void)const " (?GetX@Point@@QBENXZ) already defined in CppSandbox.obj
(每个get/set方法都有一个,据说它们都出现在Point.obj)
最后这个错误:
error LNK1169: one or more multiply defined symbols found
据报道发生在CppSandbox.exe.我不确定导致此错误的原因 - 它似乎发生在我构建或重建解决方案时......说实话,真的不知所措.
下面的三个文件是我添加到默认VS2010空白项目的全部内容(它们是完整复制的).谢谢你尽你所能的帮助.
Point.h
class Point
{
public:
Point()
{
x = 0;
y = 0;
};
Point(double xv, double yv)
{
x = xv;
y = yv;
};
double GetX() const;
void SetX(double nval);
double GetY() const;
void SetY(double nval);
bool operator==(const Point &other)
{
return GetX() == other.GetX() && GetY() == other.GetY();
}
bool operator!=(const Point &other)
{
return !(*this == other);
}
private:
double x;
double y;
};
Run Code Online (Sandbox Code Playgroud)
Point.cpp
#include "Point.h"
double Point::GetX() const
{
return x;
}
double Point::GetY() const
{
return y;
}
void Point::SetX(double nv)
{
x = nv;
}
void Point::SetY(double nv)
{
y = nv;
}
Run Code Online (Sandbox Code Playgroud)
CppSandbox.cpp
// CppSandbox.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "Point.cpp"
int main()
{
Point p(1, 2);
Point q(1, 2);
Point r(2, 3);
if (p == q) std::cout << "P == Q";
if (q == p) std::cout << "Equality is commutative";
if (p == r || q == r) std::cout << "Equality is broken";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题出在CppSandbox.cpp中:
#include "Point.cpp"
Run Code Online (Sandbox Code Playgroud)
您包含cpp文件而不是头文件,因此其内容被编译两次,因此其中的所有内容都定义了两次.(当它是一次编译Point.cpp被编译,并在第二次CppSandbox.cpp编译.)
您应该在CppSandbox.cpp中包含头文件:
#include "Point.h"
Run Code Online (Sandbox Code Playgroud)
您的头文件也应该包含防护.
| 归档时间: |
|
| 查看次数: |
2954 次 |
| 最近记录: |