我在C ++中有这个程序。

ref2.h:

#ifndef REF2_H
#define REF2_H
#include <iostream>
using std::cout;
using std::endl;

int   add_int_int(int a, int b) {return (a+b);}

class IntClass;

class Number {
    public:

        //return a Number object that's the results of x+this, when x is IntClass
        virtual Number& addInt(IntClass& x) = 0;

        //Print the number stored in the object
        virtual void print_number() = 0;
    }

class IntClass : public Number {

    private:
        int my_number;

    public:
        //Constructor
        IntClass(int n):my_number(n) {}

        //returns the number stored in the object
        int get_number()  {return my_number;}

        //print the number stored in the object
        void print_number() {cout << my_number << endl;}

        Number& addInt(IntClass& x);
    }

Number& IntClass::addInt(IntClass& x)
{
    int n = add_int_int(my_number, x.get_number());
    IntClass elem = IntClass(n);
    IntClass &ref = elem;
    return ref;
}

#endif


测试文件

#include "ref2.h"
#include <iostream>
using std::cout;
using std::endl;


int main() {
    cout << "Testing subtyping polymorphism:" << endl;
    IntClass ia(1);
    IntClass ib(2);
    Number& num = ia.addInt(ib);     num.print_number();  //should be: 3
}


我没有发现我的错误。
有谁能帮助我吗?

最佳答案

您将在addInt()中返回对局部变量的引用。不要那样做编译器应该已经警告过您。

10-06 12:35