C++ static方法调用
各位牛虾,小弟初学C++,在看到单例模式的例子,有些疑问
先看看小弟的理解:
c++中static方法应该只能调用静态的成员。
如下代码:
class Log
{
public:
virtual ~Log();
static Log* createLog(const string &sFilename);
...
protected:
private:
static Log* ownInstance;
Log();
};
Log* Log::createLog(const string &sFilename)
{
if (ownInstance != NULL)
{
return ownInstance; //这里是static方法调用的静态的成员变量
}
ownInstance = new Log(); //疑问在这里,Log()这里不是应该是非静态的成员吗?
outStream.open(sFilename.c_str(), ios::app);
if (outStream == NULL)
{
cout << "failed to open log file" << endl;
}
return ownInstance;
}
静态的方法为什么可以调用Log类非静态函数呢? C++ 静态方法
[解决办法]
ownInstance = new Log(); //1
ownInstance = new Log; // 2
1和2一样,都是new了一个默认构造的log对象,对象的地址给 ownInstance
在C++中 new Log() 和 Log()的区别是?
-----------------------------
new log() 动态创建一个log对象 ,类似 int* p = new int
log() 创建一个log 对象 ,类似 int a = int(5) , int a = 5
一个是在堆中动态创建,一个是在栈中创建。