gpt4 book ai didi

c++ - obj1是如何被引用的,如果为NULL则调用show方法

转载 作者:行者123 更新时间:2023-12-02 11:01:40 25 4
gpt4 key购买 nike

我正在尝试创建一个只能允许一次创建一个对象的类,因此我创建了私有(private)构造函数和一个公共(public)包装器 getInstance() 方法,该方法将为此类创建对象,代码如下

#include <iostream>
using namespace std;
class sample
{
static int cnt;
int temp;
private: sample()
{
//temp++;
cnt++;
cout<<"Created "<<++temp<<endl;
}
public:
void show()
{

cout<<"Showing \n";
}

static sample* getInstance()
{
cout<<"count is "<<cnt<<endl;
if(cnt<1)
return (new sample());
else
return NULL;
}

};
int sample::cnt=0;
int main()
{
// cout<<"Hello World";
sample *obj = sample::getInstance();
obj->show();

sample *obj1 = sample::getInstance();
if(obj1 == NULL)
cout<<"Object is NULL\n";
obj1->show();

return 0;
}

obj1->show() 是如何被调用的?
输出:

count is 0
Created 1
Showing
count is 1
Object is NULL
Showing

最佳答案

在真空中,这只是因为你的功能:

public:
void show()
{

cout<<"Showing \n";
}

实际上不要尝试对对象做任何事情 - 要正确理解为什么它有效,只需将成员函数视为对自由函数的抽象,以对象本身为基础第一个参数:

void show(Object* this)
{

cout<<"Showing \n";
}

现在很容易明白为什么这是有效的,因为您不使用 this - 空指针。

如果你改变一些东西。这个:

public:
void show()
{

cout<< this->temp << "Showing \n";
}

你的程序几乎肯定会崩溃。

关于c++ - obj1是如何被引用的,如果为NULL则调用show方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com