gpt4 book ai didi

c++ - 类局部变量的指针?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:47 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

做这样的代码(getIDs()返回一个指针)是否有令人担忧的事情:

class Worker{
private:
int workerID;
int departID;
int supervisorID;
public:
Worker()
{
workerID=0;
departID=0;
supervisorID=0;
name="anonymous";
workerAddress="none";
}

void setIDs(int worker, int depart, int supervisor)
{
workerID=worker;
departID=depart;
supervisorID=supervisor;
}

int* getIDs()
{
int id[3];
id[0]=workerID;
id[1]=departID;
id[2]=supervisorID;
return id;
}
};

然后,这样使用它:

Worker obj;
obj.setIDs(11,22,33);
cout<<(*obj.getIDs())<<endl;
cout<<++(*obj.getIDs())<<endl;
cout<<++(++(*obj.getIDs()))<<endl;

我对此感到疑惑,因为编译器显示:

Warning 1 warning C4172: returning address of local variable or temporary

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