![](/img/trans.png)
[英]Is there a way you can create an instance of a class that resides within another class?
[英]How can I create an instance of a class within another class?
我在 C++ 中為 3 維向量代數編寫了 class ,我想在另一個 class 三角形中使用它來定義其頂點。 編譯我的 class 時,我得到“Triangle::vert 使用未定義的 class Vec3”。
我將如何解決這個問題? 谷歌搜索似乎成員初始化列表可能是解決方案,盡管我似乎無法正確理解。 在創建三角形 class 之前,我可以初始化 Vec3 對象並在 main 中對它們使用代數函數,但在創建三角形 class 之后,我無法再在 main 中實例化 Vec3 ZA8CFDE6331BD59EB2AC96F8911C4B66。 任何幫助將非常感激:)
以下是相關代碼的一部分:
三角形.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;
}
主文件
#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 似乎發生了一些變化。 為了確定是這種情況 - 嘗試在沒有 Triangle 的情況下重建項目並重新測試 Vec3。
如需更多幫助,請上傳 Vec3.cpp 的代碼,以及 Vec3 在 main 上的工作用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.