gpt4 book ai didi

c++ - 在 C++ 中无效使用类?

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:51 25 4
gpt4 key购买 nike

嗨,我正在尝试将一些值传递给一个类,但它不会让我说无效使用类“图”我正在尝试发送 3 个值 x、y、z,仅此而已,但它不会让我继承我正在尝试的内容做...

这里是main.cpp和调用类Figure的函数

 for (j = 0; j < num_elems; j++) {
/* grab and element from the file */
vlist[j] = (Vertex *) malloc (sizeof (Vertex));
ply_get_element (ply, (void *) vlist[j]);


int vert=sprintf(szFile,"vertex: %g %g %g", vlist[j]->x, vlist[j]->y, vlist[j]->z);
/* print out vertex x,y,z for debugging */
TextOut(hDC,600,j*20,szFile,vert);
DrawFig->Figure(vlist[j]->x, vlist[j]->y, vlist[j]->z);
}

错误在这里

   DrawFig->Figure(vlist[j]->x, vlist[j]->y, vlist[j]->z);
}

这是 WM_CREATE:我在这里初始化一切

case WM_CREATE:
hDC = GetDC(hWnd);
//ShowWindow(g_hwndDlg,SW_SHOW);
hRC=wglCreateContext(hDC);
wglMakeCurrent(hDC,hRC);
g_hwndDlg = CreateDialog(hInst,MAKEINTRESOURCE(IDD_DIALOG1),hWnd,DialogProc);

DrawFig= new Figure(1.0,1.0,1.0);
initGL();
break;

这是图.h

class Figure
{
public:
Figure(float x,float y,float z);
void Draw();
float paramx(){
return x1;
}
float paramy(){
return y1;
}
float paramz(){
return z1;
}
protected:
private:
float x1,y1,z1;
list <Figure> m_vertices;
};

这是 Figure.cpp

Figure::Figure(float x,float y,float z){
this->x1=x;
this->y1=y;
this->z1=z;
m_vertices.push_back(Figure(x1, y1, z1));
}

void Figure::Draw()
{
list<Figure>::iterator p = m_vertices.begin();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();
gluLookAt(0.0,0.0,4.0,0.0,0.0,0.0,0.0,1.0,0.0);

glColor3f(0.7f,1.0f,0.3f);
glBegin(GL_LINE_LOOP);
while(p != m_vertices.end()){
glNormal3f(p->paramx(),p->paramy(),p->paramz());
glVertex3f(p->paramx(),p->paramy(),p->paramz());
p++;
}
glEnd();
}

有什么想法吗?这是 opengl、c++ 和 im 使用 codeblocks 10.05 以防万一哦,是的,我在 main.h 中初始化它,就像这个 DrawFig* 图;

最佳答案

@dark_charlie 的回答几乎是正确的。这是一个更好的版本,可以实际使用,但仍然可能不是您想要的:

class Figure  {
// ...
public:
void set(float x, float y, float z);
// ...
};

void Figure::set(float x, float y, float z)
{
// Your original code from the constructor
this->x1 = x;
this->y1 = y;
this->z1 = z;
}

Figure::Figure(float x, float y, float z)
{
// In the constructor call the newly created set function
set(x, y, z);
m_vertices.push_back(Figure(x1, y1, z1));
}


// Replace the faulty line with this:
DrawFig->set(vlist[j]->x, vlist[j]->y, vlist[j]->z);

现在,这几乎肯定不是您想要的。但也很难弄清楚你到底想要什么。你有一个设计问题。设计问题是 Figure有两个职责。它既是空间中的一个点,又是一组描述图形的点。这种职责混淆导致您的类(class)实际上无法很好地履行其中任何一项职责。

你需要两个类。您需要一个 Point 类和一个 Figure 类。 Figure 类应该允许您设置图形的位置以及向图形的轮廓添加点。

出现问题的巨大线索是 list<Figure> m_vertices; .一个类在概念上包含其自身的实例是非常罕见的。通常当您这样做时,您正在构建自己的数据结构,如树或列表,然后该类包含指向其自身实例的指针。

此外,@dark_charlie 的简单修复导致了无限递归,这一事实是另一个重要线索,表明存在问题。

我猜这是一项家庭作业,所以除了告诉你我认为你已经有一个 Point 之外,这就是我能给你的所有帮助。您调用的类 Vertex .

关于c++ - 在 C++ 中无效使用类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3800179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com