所以我对这是如何工作有点困惑。我已经按照其他例子提出以下建议:
//in entity.h
#pragma once
class Entity
{
int nEntity;
};
//in entity.cpp
#include "entity.h"
Entity::Entity
{
nEntity = 5;
}
我不确定为什么编译器不喜欢它。任何提示?
答案 0 :(得分:0)
我看到了几个问题。
在.h文件中:
class Entity
{
Entity(); // Add this.
int nEntity;
};
在.cpp文件中:
Entity::Entity() // Need the parentheses
{
nEntity = 5;
}
答案 1 :(得分:0)
看起来你正在尝试创建所谓的“构造函数”,这是一个被称为创建Entity
的新副本的函数。这里要解决两件事:
这应该有效:
class Entity
{
public: // by default, everything is "private" and only available to
// Entity itself. By adding this line here, everything that
// follows can be used anywhere
Entity(); // this "forward declares" that you're going to have a
// constructor with no arguments
int nEntity; // usually variables are marked "private," but I have a
// feeling you'll want to keep it public for a bit, until
// you get used to classes
};
Entity::Entity()
{
nEntity = 5;
}
并且,作为额外的功劳,您还可以使用特殊表示法为类成员分配值,这只能在构造函数中使用(没有其他函数可以使用此表示法)。它们有一些优点,解释起来相当棘手,但是如果你养成使用这种符号的习惯,它会对你有所帮助
Entity::Entity()
: nEntity(5)
{
// no extra instructions here. The assignment was done on the
// line starting with a colon!
}