我得到一个“非静态成员引用必须相对于特定对象".DLL项目C ++中的错误 [英] I get a "nonstatic member reference must be relative to specific object" error in a DLL project C++
问题描述
我正在处理DLL项目,正在编写一个类,其标题中包含变量和函数,并在.cpp文件中定义如下:
I'm working on a DLL project, I'm writing a class with variables and functions in a header and the definitions in a .cpp file like this:
.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()中的相同位置给了我未解决的外部符号错误.我该怎么做才能解决此问题?
OK, so in the constructor I have no problems, but in the getPoint()
function I get the "non-static member reference must be relative to specific object" error and it won't let me use the variables. I tried making the variables static, but that gives me unresolved external symbol errors in the same places, in getPoint().
What should I do to fix this?
推荐答案
它不会让我使用变量
it won't let me use the variables
您无法从 Point :: getPoint访问
X
, Y
, Z
和 alpha
,因为 getPoint
函数是静态的.静态成员函数无法访问实例数据成员,但可以访问 static
类成员.
You cannot access X
, Y
, Z
, and alpha
from Point::getPoint
because the getPoint
function is static. A static member function cannot access instance data members but it can access static
class members.
我尝试将变量设为静态,但这给了我无法解决的外部符号错误
I tried making the variables static, but that gives me unresolved external symbol errors
仅通过添加 static
关键字就无法使成员成为静态成员,还需要定义它们(例如, double Point :: X;
).
You cannot make the members static by simply adding the static
keyword, you need to define them as well (e.g., double Point::X;
).
该如何解决?
将 getPoint
函数设为非静态,并将其更新为使用引用.
Make the getPoint
function non-static and updated it to use references.
void Point::getPoint(double& x, double& y, double& z, float& a)
{
x = X;
y = Y;
z = Z;
a = alpha;
}
如果您不使用参数引用,则函数完成后更改将丢失,因为参数是按值传递的(即,它们是原始副本),这将修改仅存在于范围内的临时变量 getPoint
函数的功能.
If you don't use references for the parameters the changes are lost after the function completes because the parameters are passed by-value (i.e., they are copies of the originals) which is modifying temporary variables that only exist within the scope of the getPoint
function.
这篇关于我得到一个“非静态成员引用必须相对于特定对象".DLL项目C ++中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!