如何在另一个类中创建类的实例?

How can I create an instance of a class within another class?

本文关键字:实例 创建 另一个      更新时间:2023-10-16

我已经用C++写了一个用于三维向量代数的类,我想在另一个类三角形中使用它来定义它的顶点。编译我的类时,我得到"三角形::vert使用未定义的类Vec3"。

我将如何解决这个问题?谷歌搜索它似乎成员初始值设定项列表可能是解决方案,尽管我似乎无法正确处理。在创建三角形类之前,我可以启动 Vec3 对象并在 main 中使用代数函数,但在创建三角形类后,我无法再在 main 中实例化 Vec3 对象。任何帮助将不胜感激:)

以下是相关代码的一部分:

三角形.h

#include "Vec3.h"
class Triangle
{
public:
/*----- Variables -----*/
Vec3 vert; //Vertices, error occurs here
unsigned r, g, b; //Color

/*----- Constructors -----*/
Triangle();
};

三角形.cpp

#include "Triangle.h"
Triangle::Triangle()
{
vert.x = vert.y = vert.z = 0.0;
r = g = b = 0;
}

Vec3.h

#include <cmath>
class Vec3
{
public:
/*----- Variables -----*/
float x, y, z;
/*----- Constructors -----*/
Vec3();
Vec3(const float a);
Vec3(const float xx, const float yy, const float zz);

三角形.cpp

#include "Vec3.h"
/*----- Constructors -----*/
Vec3::Vec3()
{
Vec3::x = Vec3::y = Vec3::z = 0;
}
Vec3::Vec3(const float a)
{
Vec3::x = Vec3::y = Vec3::z = a;
}
Vec3::Vec3(const float xx, const float yy, const float zz)
{
Vec3::x = xx; Vec3::y = yy; Vec3::z = zz;
}

主.cpp

#include "Vec3.h"
#include "Triangle.h"
#include <iostream>
int main()
{
Vec3 v1(-2.0f,3.0f,3.0f); //Error here:
//Line 7: 1. "v1 uses undefined class Vec3"
//Line 7: 2. "initializing: cannot convert from initializer list to int"
Triangle t1(1,2,3);
std::cout << t1.vert.x << " " << t1.vert.y << " " << t1.vert.z;
return 0;

请注意,我没有粘贴所有函数,因为它们似乎工作正常,构造函数和初始化似乎是问题所在。

从您的描述来看,自从您上次在 main 上成功测试以来,Vec3 似乎发生了一些变化。 为了确保是这种情况 - 尝试在没有三角形的情况下重建项目并重新测试 Vec3。

如需进一步帮助,请上传 Vec3.cpp 的代码,以及 Vec3 在 main 上的工作用法。