时间:2025-08-06 21:45
人气:
作者:admin

#include<iostream>
#include<string>
#include<vector>
class Node
{
public:
Node(std::string s, int n)
{
name = (char*)malloc(10);
strcpy_s(name, 10, s.c_str());
num = n;
}
std::string GetName() {return name;}
const char* GetNameCstr() {return name;}
int GetNum() { return num; }
std::vector<Node*> GetChildNodes() {return childNodes;}
char* name;
int num;
std::vector<Node*> childNodes;
};
Node* A, * B, * C, * D, * E, * F, * G, * H;
void initializeNodes()
{
A = new Node("A", 0);
B = new Node("B", 1);
C = new Node("C", 2);
D = new Node("D", 3);
E = new Node("E", 4);
F = new Node("F", 5);
G = new Node("G", 6);
H = new Node("H", 7);
A->childNodes.push_back(B);
A->childNodes.push_back(C);
B->childNodes.push_back(D);
B->childNodes.push_back(E);
B->childNodes.push_back(F);
C->childNodes.push_back(G);
E->childNodes.push_back(H);
}
const char* findNodeNameByNum(Node* node, int num)
{
const char* n = node->GetName().c_str();
if (node->GetNum() == num)
return n;
for (auto* n : node->GetChildNodes())
{
const char* result = findNodeNameByNum(n, num);
if (result != nullptr)
return result;
}
return nullptr;
}
int findNodeNumByName(Node* node, const char* name)
{
//std::cout << name << ":" << (void*)name << std::endl;
if (strcmp(node->GetName().c_str(), name) == 0)
return node->num;
for (auto* n : node->GetChildNodes())
{
int result = findNodeNumByName(n, name);
if (result != -1)
return result;
}
return -1;
}
int main()
{
initializeNodes();
std::cout << "Please input number you want to find:" << std::endl;
int n;
while (std::cin>> n)
{
if (n<0||n>7) break;
const char* name = findNodeNameByNum(A, n);
std::cout << "find: " << findNodeNumByName(A, name) << std::endl;
}
return 0;
}

struct DebugString : public std::string {
DebugString(const char* s) : std::string(s) {
std::cout << "Constructed: " << c_str() << ":" << (void*)c_str() << "\n";
}
~DebugString() {
std::cout << "Destroyed: " << c_str() << "\n";
}
};
class Node
{
.....
DebugString GetName() {return name;}
.....
}
以0为例发现,第一次findNodeNameByNum,找到A节点名字的临时指针为FA50,然后析构后为空,传入findNodeNumByName,函数中首先对A节点查找name,并再次在FA50地址中赋值,所以判断为相等,返回相应的值。

再以6为例发现, D/E/G 构造的地址都相同,都为FAC0;B,C构造的地址相同,都为FB70;所以当传入的是6,为G的地址,在第二次循环的时候,D/E/G还在原来的地址上构造,导致先返回D的地址为3.

同理,传入的是B,C的值,先返回的都是B的值,如下图所示

由于H(7),并没有在其他重复地址上构建,所以H(7)能返回正确的值。
[注]: 以上程序为在windows平台,Release/X64下测试通过,由于std::string具体在哪里构造不可控,更换平台/架构不一定有相似输出