c++ - 我在 DLL 项目 C++ 中收到 "nonstatic member reference must be relative to specific object"错误

标签 c++ class variables dll non-static

我正在开发一个 DLL 项目,我正在编写一个类,其中的变量和函数位于 header 中,定义位于 .cpp 文件中,如下所示:

.h:

#ifndef RE_MATH_H
#define RE_MATH_H
#ifdef MATHFUNCSDLL_EXPORTS
#define RE_MATH_API __declspec(dllimport) 
#else
#define RE_MATH_API __declspec(dllexport) 
#endif
#define PI 3.14159265358979323846

namespace RE_Math
{
    class RE_MATH_API Point
    {
        public:
            double X;
            double Y;
            double Z;
            float alpha;

            Point(double x, double y, double z, float a);
            static void getPoint(double x, double y, double z, float a);
    };
}

和.cpp:

#include <re_math.h>

namespace RE_Math
{
    Point::Point(double x, double y, double z, float a)
    {
        X = x;
        Y = y;
        Z = z;
        alpha = a;
    }

    void Point::getPoint(double x, double y, double z, float a)
    {
        x = X;
        y = Y;
        z = Z;
        a = alpha;
    }
}

好的,所以在构造函数中我没有问题,但是在 getPoint() 函数中我得到了“非静态成员引用必须相对于特定对象”错误并且它不会让我使用变量。我尝试使变量成为静态变量,但这在相同的位置(在 getPoint() 中)给我带来了 Unresolved external symbol 错误。 我应该怎么做才能解决这个问题?

最佳答案

it won't let me use the variables

您不能从 Point::getPoint 访问 XYZalpha 因为 getPoint 函数是静态的。静态成员函数不能访问实例数据成员,但它可以访问 static 类成员。

I tried making the variables static, but that gives me unresolved external symbol errors

您不能通过简单地添加 static 关键字来使成员成为静态成员,您还需要定义它们(例如,double Point::X;)。

What should I do to fix this?

使 getPoint 函数成为非静态函数并更新它以使用引用。

void Point::getPoint(double& x, double& y, double& z, float& a)
{
    x = X;
    y = Y;
    z = Z;
    a = alpha;
}

如果您不对参数使用引用,函数完成后更改将丢失,因为参数是按值传递的(即,它们是原始参数的拷贝),这会修改仅存在于范围内的临时变量getPoint 函数。

关于c++ - 我在 DLL 项目 C++ 中收到 "nonstatic member reference must be relative to specific object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145335/

相关文章:

c++ - 如何使用基地址来获取动态?

c++ - 命名空间定义和异常(exception)

python - 试图从一个类中调用一个对象

javascript - 取出函数中的值(javascript)

c++ - 为什么此代码不创建竞争条件?

c++ - 向 QML 应用程序发送键盘事件

c++ - 在 gcc 中使用结构作为 SSE vector 类型?

typescript - 在 TypeScript 中将类函数作为参数传递并引用静态成员

php 用中间的连字符组合变量

c++ - 如何从 C 中的字符中减去整数?