为什么我在向类[C++]添加私有变量时出错

Why am i getting an error when adding private variable to class [C++]

本文关键字:添加 变量 出错 C++ 为什么      更新时间:2023-10-16

我有一个网格类,它分布在两个文件(mesh.h和mesh.cpp)上。现在它工作得很好,直到我添加了一个位置变量(类型为Vector2d)。当我添加变量时,它仍然正常运行,但当我在其中一个函数中使用它时,它给了我一个错误,说我的一堆变量没有声明。让我给你看看我到底做了什么:

class Mesh{
public:
Mesh() {
Rectangle;
position = Vector2d(0,0);
}
Mesh(Vector2dVector Vertices) {
Set(Vertices);
position = Vector2d(0,0);
};
Vector2dVector GetVetices() { return vertices; };
Vector2d SetPosition(Vector2d p) { position = p; }
float GetVertexCount() { return vertexCount; };
float GetTriangleCount() { return triangleCount; }
void  Set(Vector2dVector Vertices){
Triangulate::Process(Vertices,vertices);
vertexCount = vertices.size();
triangleCount = vertexCount/3;
};
void Render();
static Mesh Circle();
static Mesh Rectangle();
static Mesh Triangle();
private:
Vector2dVector vertices;
Vector2d position;
int triangleCount;
int vertexCount;
};

这运行正常,但当我将其添加到文件mesh.cpp的函数渲染中时,它给了我一个错误

#include "mesh.h"
void Mesh::Render() {
glBegin (GL_TRIANGLES); 
for (int i=0; i<GetTriangleCount(); i++) {
const Vector2d &p1 = vertices[i*3+0];
const Vector2d &p2 = vertices[i*3+1];
const Vector2d &p3 = vertices[i*3+2];
glVertex2f(position.GetX() + p1.GetX(),position.GetY() + p1.GetY());
glVertex2f(position.GetX() + p2.GetX(),position.GetY() + p2.GetY());
glVertex2f(position.GetX() + p3.GetX(),position.GetY() + p3.GetY());
}
glEnd ();
}

这是错误信息

In file included from main.cpp:3:
mesh.h: In constructor `Mesh::Mesh()':
mesh.h:5: error: no matching function for call to `Vector2d::Vector2d()'
triangulation.h:43: note: candidates are: Vector2d::Vector2d(const Vector2d&)
triangulation.h:46: note:                 Vector2d::Vector2d(float, float)
mesh.h: In constructor `Mesh::Mesh(Vector2dVector)':
mesh.h:10: error: no matching function for call to `Vector2d::Vector2d()'

所以在我删除了所有的位置之后。收到方法调用函数时,它仍然给了我相同的错误事件,尽管在我添加和删除之前没有。我已经用电脑工作了大约4年了,我从来没有见过我的电脑会这样。如果有人能向我解释我做错了什么,那将非常有帮助。顺便说一句,我使用的是DevC++4.9.9.2版本,所以我认为这与此有关。

谢谢你的阅读,很抱歉太长了。

您有一个Mesh::Mesh()构造函数。编译器抱怨它无法为Vector2d类(为position实例变量)调用适当的构造函数(没有参数)。您必须:

  • 提供Vector2d::Vector2d()构造函数,或者
  • 使用Mesh::Mesh()中的适当参数为position调用一个现有的Vector2d构造函数,如下所示:

    Mesh(): position(0, 0) {
    }
    

    (我去掉了Rectangle;,因为按照写的那样,这不会有任何效果。你可能想用Rectangle();调用那个函数吗?)

您必须在构造函数的初始化器列表中初始化向量,而不是在构造函数体中:

Mesh(): position(0,0) {
Rectangle;
}
Mesh(Vector2dVector Vertices) : position(0,0) {
Set(Vertices);
};

否则position将被默认构造,这将失败,因为您没有定义默认构造函数。