使用包含指针的队列时出现奇怪的行为

Moh*_*hdi 0 c++ queue pointers stl

我正在尝试创建一个二叉树,当您尝试向其添加新节点时,它会将节点添加到第一个位置nullptr.

实际上制作一个完整的二叉树.

看下面的代码:

#include <iostream>
#include <queue>
using namespace std;

class node{
private:
    char data;
    node* right;
    node* left;
public:
    node(char n){
        data = n;
        left = nullptr;
        right = nullptr;
    }
    char getdata(){
        return data;
    }
friend class binTree;
};

class binTree{
private:
    node *root;
public:
    binTree(){
        root = nullptr;
    }
    binTree(node *root){
    this->root = root;
    }

    node* getRoot(){
    return this->root;
    }


    void addNode(char data){
        cout << "adding " << data << endl;

        if(root == nullptr) {
            root = new node(data);
            return;
        }


        queue<node*> Q;
        Q.push(root);
        node* toadd;
        while(true) {
            node* toadd = Q.front();
            Q.pop();
            Q.push(toadd->left);
            Q.push(toadd->right);

            if(toadd->left == nullptr)  break;
            if(toadd->right == nullptr) break;
        }

        if((toadd->left) == nullptr)
        {
            cout << "add data to the left of " << toadd -> data << endl;
            toadd->left = new node(data);
        } else if((toadd -> right) == nullptr){
            cout << "add data to the right of " << toadd -> data << endl;
            toadd->right = new node(data);
        } else {
            cout << "toadd left and right are not nullptr" << endl;
        }

    }
};

int main()
{
    binTree bin;
    string s = "abcdefg";
    cout << s << endl << endl;
    for(int i = 0; i < s.size(); i++)
    {
        bin.addNode(s[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时输出为:

abcdefg

adding a
adding b
toadd left and right are not nullptr
adding c
toadd left and right are not nullptr
adding d
toadd left and right are not nullptr
adding e
toadd left and right are not nullptr
adding f
toadd left and right are not nullptr
adding g
toadd left and right are not nullptr
Run Code Online (Sandbox Code Playgroud)

奇怪的是当打印"toadd left and right are not nullptr"时因为有一段时间(true)而唯一的退出条件是:

            if(toadd->left == nullptr)  break;
            if(toadd->right == nullptr) break;
Run Code Online (Sandbox Code Playgroud)

所以其中一个条件是真的,我们可以打破循环; 所以我们应该输入以下代码中的一个ifelse if部分代码(在while之后),但令人惊讶的是我们输入else打印的部分和结尾"toadd left and right are not nullptr".有谁能解释这种行为?

Mar*_*som 6

你已经定义了toadd两次,一次是在循环之前,一次是在内部.容易犯错误.

  • gcc和clang上的`-Werror = shadow`避免了这类错误. (5认同)