我最近写了几堂课; 我想知道这是不好的做法,对性能有害,打破封装,还是在标题中实际定义一些较小的成员函数是否还有其他任何不妥之处(我确实试过谷歌!).这是一个我有一个标题的例子我写了很多这个:
class Scheduler {
public:
typedef std::list<BSubsystem*> SubsystemList;
// Make sure the pointer to entityManager is zero on init
// so that we can check if one has been attached in Tick()
Scheduler() : entityManager(0) { }
// Attaches a manager to the scheduler - used by Tick()
void AttachEntityManager( EntityManager &em )
{ entityManager = &em; }
// Detaches the entityManager from a scheduler.
void DetachEntityManager()
{ entityManager = 0; }
// Adds a subsystem to …Run Code Online (Sandbox Code Playgroud) 我今天正在重读c ++入门(第4版) - 关于成员函数和const引用的部分等,我想出了这个奇怪的小程序:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
int value;
private:
ConstCheater* ccp;
};
int main()
{
const ConstCheater cc(7); //Initialize the value to 7
cout << cc.value << endl;
cc.getccp().value = 4; //Now setting it to 4, even though it's const!
cout << cc.value << endl;
cc.value = 4; //This is illegal
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 - 为什么c ++允许这样的语法?为什么我可以在类声明为const时编辑类中的普通数据成员?是不是const的POINT使它不能修改值?