为什么我在向类[C++]添加私有变量时出错
Why am i getting an error when adding private variable to class [C++]
我有一个网格类,它分布在两个文件(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
将被默认构造,这将失败,因为您没有定义默认构造函数。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 将布尔变量添加到 int
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 尝试将带有值的不同变量添加到一小串程序C++中
- 将不同类型的变量添加到向量中
- 如何添加依赖于类本身的模板成员变量
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- OPC-UA open62541 sdk 运行服务器后动态添加变量节点
- 您可以在内部添加变量
- C++在if函数中添加变量
- C++ Linux 套接字在字符 *msg 中添加变量
- 在C 中动态添加变量
- 向字符串中添加变量和文本
- Cplex C++按列添加变量(库存)
- 在链表形成中,在开头添加变量的代码是什么
- 我正在尝试在变量中添加变量"height" "media"
- c++ fstream -如何在.open()中添加变量而不是字符串
- 无法在mfc中看到添加变量向导
- C++ - 根据模板参数向模板化类添加变量和函数