尝试打印对象名称时程序崩溃

时间:2017-09-29 14:37:47

标签: c++

作为练习,我试图通过有序链接列表来实现河内塔。我已经创建了列表,棒和盘类。一切正常,河内塔也是如此。 当我想要打印杆名时会出现问题。我想打印类似的东西:

Move Disc A to disc C
Move Disc A to disc B

由于我无法直接打印对象名,因此构建了Rod类构造函数以给对象一个名称,但是当我尝试在Hanoi类中调用getName方法时,或者重载运算符<<在Rod课程中程序崩溃。这是我的代码,我省略了列表,广告磁盘类。

class Rod{
    private:
        OList<Disc> *r;
        char name;

        void _add(Disc x){
          r->insert(x);
        }

        void _print(){
        r->print();
        }

        void _rm(){
        r->rmDisc();
        }
    public:
        Rod(char name){
            r = new OList<Disc>();
            this->name = name;
        }

        Paletto *add(Disc x){
            _add(x);
            return this;
        }

        Disco *del(){
            _rm();
        }

        Paletto *moveTo(Rod *d){
            Disc *disc = del();
            d->add( *disc );
            return this;
        }


        void print(){
            _print();
        }

        char getName(){
            return name;
        }

        friend ostream &operator<<(ostream &os,Rod &p){
            os<<p.getName();
            return os;
        }

};

class Hanoi{
    private:
        int n;
        Rod *A,*B,*C;
        void hanoiTower(int disc,Rod  *start,Rod *end,Rod *aux){
            if(disc == 1){
                cout<<"Move disc from "<<*start<<" to "<<*end<<endl;
                return;
            }
            else{
                hanoiTower(disc - 1,start,aux,end);
                cout<<"Move disc from "<<*start<<" to "<<*end<<endl;
                hanoiTower(disc - 1,aux,end,start);
            }
        }   
    public:
        Hanoi(int n){
            this->n = n;
            Rod *A = new Rod ('A');
            Rod *B = new Rod ('B');
            Rod *C = new Rod ('C');
        }

    void solve(){
        hanoiTower(n,A,B,C);
    }   
    int moves(){
        return pow(2,n)-1;
    }
}; 

该程序执行动作,直到我尝试打印给定名称的类,否则崩溃。我在这里遗漏了什么?如果我的问题看起来过于笼统或不完整,我会提前道歉。

0 个答案:

没有答案