c++中类的虚函数与引用赋值问题

class Shape{
public:
    virtual int fun()=0;
};
class Rec:public Shape{
    int x,y;
public:
    Rec(int a,int b){
        x=a;
        y=b;
    }
    void Set(int a,int b){
        x=a;
        y=b;
    }
   virtual int fun(){
        return x*y;
    }

};
void main(){
     Rec r1(1,1);
     Rec r2(10,10); 
     Shape &p=r1;
     r1=r2; 
     cout<<p.fun()<<endl; //输出x*y=100

     r1.Set(1,1);
     cout<<p.fun()<<endl;  //输出x*y=1
     p=r2;
     cout<<p.fun()<<endl;  //输出x*y=1,为什么不是输出100?????????
     while(1);
}

可是如果对int型进行引用的话,
int a=1,b=2;
int &p=a;
cout<<a<<p<<endl; //输出1,1
p=b;
cout<<a<<p<<endl; //输出2,2
a=3;
cout<<a<<p<<endl; //输出3,3
无论是改变a还是p他们俩都会一起改变,跟上面的类的引用不一样

r1地址 和p地址是否一样 不一样更改r1并不改变p

因为p是shape的引用,而不是rec的引用
Rec &p=r1;
这样输出
100
1
100

楼主,你的问题其实是调用了Shape类的默认【=算符函数】导致的,你可以试试,把Shape类的【=算符函数】在父子类中都重写一下
我试了下,代码如下,黏贴到dev里运行试试看。

#include <iostream>
#include <typeinfo.h>
using namespace std;
class Shape{
public:
    virtual int fun()=0;

    virtual Shape& operator=(const Shape&rhs)
    {
        cout<<"调用了父类中的=算符函数"<<endl;
    }
};
class Rec:public Shape{
    int x,y;
public:
    virtual Shape& operator=(const Shape&rhs)//rhs:right hand side 指'='的右边 
    {
        try{
            const Rec& rhs_casted = dynamic_cast<const Rec& >(rhs);//运行类型检查两大算符之一,如果类型转换失败,抛出一个bad_cast异常 
            *this = rhs_casted;//将rhs的静态类型(Shape&)换成Rec&后,就可以使用子类的 【=运算函数了】 

        }
        catch(std::bad_cast)
        {
            cout<<"转换失败"<<endl;
        }

        cout<<"调用了子类中的重写的【Shape&=算符函数】"<<endl;
    }
//  Rec& operator=(const Rec&rhs)//子类算符函数 
//  {
//      x=rhs.x;
//        y=rhs.y;
//        cout<<"调用了子类的=算符函数"<<endl;
//  }
    Rec(int a,int b){
        x=a;
        y=b;
    }
    void Set(int a,int b){
        x=a;
        y=b;
    }
   virtual int fun(){
        return x*y;
    }

};
int main(){
     Rec r1(1,1);
     Rec r2(10,10); 
     Shape &ref=r1;

     cout<<"------------分割线--------------"<<endl;
     ref=r2;//本意:将r2的内容刷到ref引用的区域(r1的内存区域),而不是ref换引用到r2。所以这里要调用 【=算符函数】
            //但是没有调用子类的【=算符函数】,因为没有声明virtual 
            //调用了ref的静态类型(Shape&),即父类对应的【=算符函数】,这是因为 【=算符函数】不是virtual(可以试试把上面两个virtual Shape& operator=(...){}注释掉) 
     //r1=r2;//如果ref是别名的话, 【r1=r2】与【ref=r2】应该是一样的效果才对 ,调用了【=算符函数】
     cout<<ref.fun()<<endl;  //这里把两个virtual【=算符函数】注释掉,结果不一样

     cout<<r1.fun()<<endl;  //与cout<<ref.fun()<<endl;结果一样 ,再次证明【引用】的本质是别名 
     cout<<r2.fun()<<endl;  //测试,结果合理     
     return 0;
}

ps:如果遇到代码不懂的C++语法,以下是给后来人看的。
Q:什么是静态类型?
《C++ primer 5th 》中文版
p534
Q:dynamic_cast是什么?
p730