gpt4 book ai didi

c++ - Address-of(&) 运算符传递的无效指针

转载 作者:行者123 更新时间:2023-11-28 05:55:00 26 4
gpt4 key购买 nike

好吧,我正在练习 C++ 类和指针。突然间就...如果我尝试获取在参数中传递的对象的地址,它会给我一个无效地址。

这是怎么回事?

P.S 你可以忽略 if 语句,它不应该与这个特定问题相关。 Picture of the Problem.

int ChainLinkz::chainCount = 0;

ChainLinkz::ChainLinkz(int i) {
data = i;
chainID = chainCount++;
fLink = this;
addr = this;
nLink = 0;
printf("Created Link with Value: %i Addr: %x.\n", data, this);
}

ChainLinkz *ChainLinkz::next() {
if (nLink)
return nLink;
else
return 0;
}

ChainLinkz *ChainLinkz::last() {
ChainLinkz * lastLink = fLink;
while (lastLink->next()) {
lastLink = lastLink->next();
}
return lastLink;
}

ChainLinkz ChainLinkz::addLink(ChainLinkz link) {
if (link.nLink) {
if (&link == link.fLink) { // Replace fLink with new address in all instances of previous chain | Fix the old chain
ChainLinkz *t_link = link.nLink;
while (t_link->next()) {
t_link = t_link->next();
t_link->fLink = link.nLink;
}
} else { // Replace nLink for previous link | Fix the old chain
ChainLinkz *t_link = link.fLink;
while (t_link != &link)
t_link = t_link->next();
t_link->nLink = link.next();
}
}
last()->nLink = link.addr;
printf("\n&link: %x | Real Addr: %x \n\n", (ChainLinkz*)&link, link.addr);
link.nLink = 0; //Update values to new chain
link.fLink = fLink;

return link;
}

ChainLinkz ChainLinkz::addLink(ChainLinkz *link) {
printf("Overloader: %x.\n", link);
return addLink(*link);
}

ChainLinkz ChainLinkz::operator>>(ChainLinkz link) {
return addLink(link);
}
ChainLinkz ChainLinkz::operator>>(ChainLinkz *link) {
printf("Overloader: %x.\n", link);
return addLink(*link);
}

最佳答案

通过使用引用而不是传递对象本身解决了这个问题。

ChainLinkz ChainLinkz::addLink(ChainLinkz &link) {
printf("Overloaded New: %p\n", &link);
return addLink(&link);
}

ChainLinkz ChainLinkz::addLink(ChainLinkz *link) {
if (link->nLink) {
if (link == link->fLink) { // Replace fLink with new address in all instances of previous chain | Fix the old chain
ChainLinkz *t_link = link->nLink;
while (t_link->next()) {
t_link = t_link->next();
t_link->fLink = link->nLink;
}
}
else { // Replace nLink for previous link | Fix the old chain
ChainLinkz *t_link = link->fLink;
while (t_link != link)
t_link = t_link->next();
t_link->nLink = link->next();
}
}
last()->nLink = link;
link->nLink = 0; //Update values to new chain
link->fLink = fLink;
return *link;
}

ChainLinkz ChainLinkz::operator>>(ChainLinkz &link) {
return addLink(&link);
}
ChainLinkz ChainLinkz::operator>>(ChainLinkz *link) {
printf("Overloaded: %p.\n", link);
return addLink(link);
}

关于c++ - Address-of(&) 运算符传递的无效指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34350575/

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