注册 登录
编程论坛 C++教室

新人求助,Point &p=NULL;

渐渐鱼 发布于 2018-06-01 15:02, 1441 次点击
程序代码:
#include<iostream>
using namespace std;
class Point
{
    public:
    Point(){}
    Point(int X,int Y)
    {
        x=X;
        y=Y;
    }

   virtual void set(int X,int Y)
    {
       x=X;
       y=Y;
    }
     
    virtual void display()
     {
         cout<<"x="<<x<<endl;
         cout<<"y="<<y<<endl;
     }
    protected:
    int x;
    int y;
};
class Circle:public Point
{
    public:
    Circle(){}
    Circle(int X,int Y,int Radius):Point(X,Y)
    {
        x=X;
        y=Y;
        radius=Radius;
    }
    void set(int X,int Y,int Radius)
    {
        x=X;
        y=Y;
        radius=Radius;
    }
    void display()
        {
         cout<<"x="<<x<<endl;
         cout<<"y="<<y<<endl;
         cout<<"半径="<<radius<<endl;
         }
    protected:
    int radius;
};
class Cylinder:public Circle
{
    public:
    Cylinder(){}
    Cylinder(int X,int Y,int Radius, int Height):Circle(X,Y,Radius)
    {
        x=X;
        y=Y;
        radius=Radius;
        height=Height;
    }
    void set(int X,int Y,int Radius, int Height)
    {
        x=X;
        y=Y;
        radius=Radius;
        height=Height;

    }
    void display()
    {
         cout<<"x="<<x<<endl;
         cout<<"y="<<y<<endl;
         cout<<"半径="<<radius<<endl;
         cout<<"高="<<height<<endl;
    }
    private:
    int height;
};
int main()
{
    Point &p=NULL;
    Point t;
   
    t.set(1,2);
    t.display();

    Circle c;
    Cylinder d;

    p=&c;
    c->set(1,2,3);
    c->display();

    p=&d;
    d->set(1,2,3,4);
    d->display();
   
    return 0;
}




运行结果:
/tmp/815282660/main.cpp:84:12: error: non-const lvalue reference to type 'Point' cannot bind to a temporary of type 'long'
    Point &p=NULL;
           ^ ~~~~
/tmp/815282660/main.cpp:94:6: error: member reference type 'Circle' is not a pointer; maybe you meant to use '.'?
    c->set(1,2,3);
    ~^~
     .
/tmp/815282660/main.cpp:95:6: error: member reference type 'Circle' is not a pointer; maybe you meant to use '.'?
    c->display();
    ~^~
     .
/tmp/815282660/main.cpp:98:6: error: member reference type 'Cylinder' is not a pointer; maybe you meant to use '.'?
    d->set(1,2,3,4);
    ~^~
     .
/tmp/815282660/main.cpp:99:6: error: member reference type 'Cylinder' is not a pointer; maybe you meant to use '.'?
    d->display();
    ~^~
     .
5 errors generated.

exit status 1
2 回复
#2
SMRen2018-06-02 08:43
让我这个菜鸟来回答一下吧,Point &p=NULL;p=&c;p=&d;这三条语句是不合法的,引用必须在声明时绑定被引用对象而且不能更改绑定对象,所以这三条应该去掉第一个声明,把 p=&c 替换为 Point &p = c; 把 p=&d 替换为 Point &p1 = d;但是这两条语句中的p, p1在后面并没有用到,会报警告;此外, c->set(1,2,3);  c->display();  d->set(1,2,3,4);   d->display();  中的->是用于指针的,这里要用 . ,即c.set(1,2,3);
我还没学到 virtual 关键字,所以类中的函数我不太能看懂,希望刚才说的没有说错,对你有所帮助。
1