简体   繁体   English

在构造函数中相互引用的两个类

[英]Two classes that refer to each other in their constructor

I want to create one 2-dimensional vector datatype and one 3-dimensional vector datatype, but both of them should be compatible to eachother.我想创建一个 2 维向量数据类型和一个 3 维向量数据类型,但它们都应该相互兼容。

Here are the class definitions这是 class 定义

class vec2;
class vec3;

class vec2
{
public:
    FLOAT x, y;

    vec2(FLOAT X = 0, FLOAT Y = 0)
    {
        x = X;
        y = Y;
    }

    // constructor declaration (necessary because of "use of undefined type")
    vec2(vec3 V);
};

class vec3
{
public:
    FLOAT x, y, z;

    vec3(FLOAT X = 0, FLOAT Y = 0, FLOAT Z = 0)
    {
        x = X;
        y = Y;
        z = Z;
    }

    vec3(vec2 V)
    {
        x = V.x;
        y = V.y;
        z = 0;
    }
};

vec2::vec2(vec3 V)
{
    x = V.x;
    y = V.y;
}

I want to be able to call a function like this:我希望能够像这样调用 function:

// prototypes
int func_Vec2(vec2 Position);
int func_Vec3(vec3 Space);

// create variables
vec2 myPosition(100, 100);// creates a vector "myPosition" with x = 100, y = 100
vec3 mySpace(100, 200, 300);// creates a vector "mySpace" with x = 100, y = 200, z = 300

// call functions with compatible datatypes
func_Vec2(vec2(mySpace));// mySpace is vec3 but the constructor of vec2 allows a vec3 as parameter
func_Vec3(vec3(myPosition));// myPosition is vec2 but the constructor of vec3 allows vec2 as parameter

However, no matter how much I experiment with the class definition / constructors, every try brings another error and I'm running out of ideas.但是,无论我对 class 定义/构造函数进行了多少试验,每次尝试都会带来另一个错误,而且我已经没有想法了。

Because I added因为我加了

class vec2;
class vec3;

to the top, the following linker error appears: 'LNK2005 "public: __cdecl vec2::vec2(class vec3)" already defined in main.obj'到顶部,出现以下 linker 错误:'LNK2005 "public: __cdecl vec2::vec2(class vec3)" already defined in main.obj'

But if I remove the class prototypes, this error occurs: 'C2061 syntax error vec3' (Because of constructor declaration "vec2(vec3 V);" in class vec2.但是,如果我删除 class 原型,则会发生此错误:'C2061 syntax error vec3'(由于 class vec2 中的构造函数声明“vec2(vec3 V);”。

Note that I also added请注意,我还添加了

vec2::vec2(vec3 V)
{
    x = V.x;
    y = V.y;
}

outside of the class because vec3 is not yet defined and would throw: "use of undefined type"在 class 之外,因为 vec3 尚未定义并且会抛出:“使用未定义类型”

Since vec2::vec2(vec3 V) is implemented in the.h file, make it inline .由于vec2::vec2(vec3 V)在 .h 文件中实现,因此将其设为inline

inline vec2::vec2(vec3 V)
{
    x = V.x;
    y = V.y;
}

Otherwise, every.cpp file that includes the.h file has a non-inline implementation of the constructor.否则,包含 .h 文件的每个 .cpp 文件都具有构造函数的非内联实现。 That causes the problem reported by the linker.这会导致 linker 报告的问题。

The other option will be to move the definition to a.cpp file (and not use inline ).另一个选项是将定义移动到 a.cpp 文件(而不是使用inline )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM