由(&)运算符的地址传递的无效指针

时间:2015-12-18 07:37:10

标签: c++ c++11 visual-c++

好吧,所以我正在练习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);
}

1 个答案:

答案 0 :(得分:1)

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

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);
}