c++ - 结构定义导致我收到多重定义符号错误

标签 c++ constructor struct linker

我有一个“dStructs”类,我在其中定义了几个可公开访问的结构,“实体”和“点”。这些结构在类括号 dStructs 中完全定义。但是我不确定我是否正确定义了它们的构造函数。代码看起来像这样......

#pragma once

#include <GL/glut.h>


class dStructs 
{


public:
    struct point
    {
        GLfloat x, y;

        point()
        {

        }

        point(GLfloat aX,GLfloat aY) //constructor for point
        {
            x = aX;
            y = aY;
        }
    };

    struct entity
    {
        point pos, size;

        entity()
        {

        }

        entity(GLfloat posX, GLfloat posY, GLfloat sizeX, GLfloat sizeY)
        {
            pos = point(posX,posY);
            size = point(sizeX, sizeY);
        }

    };

static void copyPoint(point pointToCopy, point& toPoint);
static void copyEntity(entity entityToCopy, entity& toEntity);

};

我在想我在将构造函数定义放在 struct brakets 中而不是在 .cpp 文件中时做错了什么。 所以我尝试将它们移出,并像这样在 .cpp 中定义它们......

#include "dStructs.h"

dStructs::point::point()
{
}

dStructs::point::point(GLfloat aX, GLfloat aY)
{
    x = aX;
    y = aY;
}

dStructs::entity::entity()
{

}

dStructs::entity::entity(GLfloat posX, GLfloat posY, GLfloat sizeX, GLfloat sizeY)
{
    pos = point(posX,posY);
    size = point(sizeX, sizeY);
}

但是,这并不令人高兴,因为无论在我的代码中使用结构“point”还是“entity”,都会导致 Unresolved external symbol 错误。

任何人都可以看到我在声明我的结构(及其相关构造函数)时出错的地方会出现此错误吗?

最佳答案

However, no joy, as this is caused unresolved external symbol errors wherever the structs 'point' or 'entity' were used in my code.

那是因为一旦您将定义移动到 .cpp 文件中,您实际上必须稍后链接到相应的对象。

即如果 myfile.cpp 使用 dStructs,你们都必须包含头文件(就像你们已经做的那样)并且:

g++ -o myprog myfile.cpp dStructs.cpp

g++ -c myfile.cpp
g++ -c dStructs.cpp
g++ -o myprog myfile.o dStructs.o

关于c++ - 结构定义导致我收到多重定义符号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523170/

相关文章:

javascript - Javascript 构造函数有什么意义?

调用包含指针参数的函数

c - 可以在声明后填充结构数组吗?

c - 在内部使用带有函数指针的结构成员

javascript - 如何使用 ffi 将 WinApi 函数加载到 Node.js 中?

c# - 如何判断一个构造函数是否被另一个构造函数调用?

c++ - 如何知道所使用的微软 C runtime 的版本?

java - Rational 类中的构造函数 Rational 无法应用于给定类型?

c++ - 通过删除重复代码使我的 do while 循环更整洁

c++ - 使用 std::array<T, N> 会导致代码膨胀吗?