使用局部对象指针的简单样式问题及其功能 [英] Simple style question using local object pointer and its function
本文介绍了使用局部对象指针的简单样式问题及其功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这种样式可以吗?
Is this style OK?
#include "BaseClass.h"
CMyClass::AFunction( CData & goodData )
{
CBaseClass * baseClass; // don''t really need an instance
baseClass->AgentFunction( goodData ); // just the use of its function
}
我喜欢简单.我注意到我无法通过嵌入CBaseClass或使用CBaseClass ::
来做到这一点
另外,我注意到我不必初始化为NULL,并且想知道我应该说= 0还是= NULL.
I like the simplicity. I noticed I couldn''t do it by embedding CBaseClass or using CBaseClass::
Also, I noticed I didn''t have to initialize to NULL, and wondered should I say = 0, or = NULL.
推荐答案
Brian Bennett写道:
Brian Bennett wrote:
CBaseClass * baseClass; //并不需要实例
baseClass-> AgentFunction(goodData); //仅使用其功能
CBaseClass * baseClass; // don''t really need an instance
baseClass->AgentFunction( goodData ); // just the use of its function
如果您喜欢简单性,为什么不使用AgentFunction
方法static
?
:)
If you like simplicity why then didn''t you make AgentFunction
method static
?
:)
您必须确保以这种方式调用的函数不使用该类的任何成员变量(全部通过其调用链).
You must make sure that a function invoked this way doesn''t make use of any member variables of that class (all through its call chain).
Cpallini的答案涵盖了静态成员函数的模拟.
如果您使用的是C ++ 98编译器,请使用0而不是NULL. 0与C ++中的任何指针类型都兼容,并且如果操作系统需要其他功能,则取决于编译器进行转换. NULL仅是C程序员的舒适毯子,并且(在我使用过的每个C ++编译器中,NULL都被定义为0).
如果您使用的是C ++ 0x,则可以使用nullptr
.这是类型为nullptr_t
的变量,该变量再次与任何其他指针类型兼容.
干杯,
灰
PS:针对以下评论...
NULL的问题在于,它为C ++中的空"指针值提供了0的尴尬感.过去C的人们认为NULL是(void *)0,但是在C ++中,这是完全垃圾.然后,当他们尝试实例化模板或使用模板调用重载函数时,他们会感到非常困惑,并且发生了一些完全棘手的事情.另一方面,如果您使用普通的旧0,那么您将毫无疑问地认为它是模棱两可的,并且在创建或调用int专业化或覆盖时,也不会因此而感到惊讶.
Cpallini''s answer covers the simulation of a static member function.
If you''re using a C++98 compiler then use 0 rather than NULL. 0 is type compatible with any pointer type in C++ and if the OS wants something else it''s up to the compiler to do the conversion. NULL is only there as a comfort blanket to C programmers and is (on every C++ compiler I''ve used, 10 of them) defined as 0.
If you''re using C++0x then you can usenullptr
. This is a variable of typenullptr_t
which, again, is type compatible with any other pointer type.
Cheers,
Ash
PS: In response to the comment below...
The problem with NULL is that it gives a fig leaf over the embarrassment of 0 for the "null" pointer value in C++. People used to C think that NULL is (void *)0, however in C++ this is complete rubbish. They then get very confused when they try and instantiate a template or call an overloaded function with it and something completely screwy happens. On the other hand if you use plain old 0 then you''ll be under no illusions that it''s ambiguous and won''t be (so) surpised when the int specialisation or override gets created or called.
这篇关于使用局部对象指针的简单样式问题及其功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文