通过指针访问成员函数

时间:2015-09-06 07:24:14

标签: c++ oop inheritance

为什么我在输出中获取地址。相反,我应该得到输出长度=(用户输入的值),宽度=(用户输入的值)。 在获得输入R1.getdata()后的程序主体中,ptr->result()应该显示Rectangle类的结果。

#include <iostream>

using namespace std;

class Rectangle {
   protected:
    float length;
    float width;

   public:
    void getdata() {
        cout << "Enter length and width= ";
        cin >> length >> width;
    }
    void result() {
        cout << "Length = " << length << "\nWidth = " << width << endl;
    }
};
class Area : public Rectangle {
   private:
    float area;

   public:
    void calc_area() { area = length * width; }
    void result() { cout << "Area = " << area << endl; }
};
class Perimeter : public Rectangle {
   private:
    float perimeter;

   public:
    void calc_peri() { perimeter = 2 * (length + width); }
    void result() { cout << "Perimeter = " << perimeter << endl; }
};
void main() {
    Rectangle R1;
    Area A1;
    Perimeter P1;
    Rectangle *ptr;
    R1.getdata();
    ptr = &A1;
    ptr->result();
}

2 个答案:

答案 0 :(得分:1)

您得到的值不正确,因为您正在未初始化的Area对象(A1)上调用ptr->result();,该对象已从指向Rectangle对象的指针上升。

用户输入的值虽然在R1对象中使用,但您不再使用它。此外,您应该将result()方法设为虚拟。

最后,在指向继承类的指针上调用基类方法的语法是ptr->Rectangle::result();

您将在下面找到一些代码,其中包含一些可以演示我所写内容的修补程序:

#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Rectangle {
   protected:
    float length;
    float width;

   public:
    void getdata() {
        cout << "Enter length and width= ";
        cin >> length >> width;
        std::cout << length << "  " << width << std::endl;
    }
    virtual void result() {
        cout << "(Rectangle) Length = " << length << "\nWidth = " << width
             << endl;
    }
};
class Area : public Rectangle {
   private:
    float area;

   public:
    void calc_area() { area = length * width; }
    void result() { cout << "Area = " << area << endl; }
};
class Perimeter : public Rectangle {
   private:
    float perimeter;

   public:
    void calc_peri() { perimeter = 2 * (length + width); }
    void result() { cout << "Perimeter = " << perimeter << endl; }
};
int main() {
    Rectangle R1;
    Area* A1;
    Perimeter P1;
    Rectangle* ptr;
    R1.getdata();
    ptr = &R1;
    A1 = static_cast<Area*>(ptr);
    // or:
    // A1 = (Area*)ptr;
    ptr->Rectangle::result();
}

答案 1 :(得分:0)

Ptr指向Rectangle类的子类的地址(Area类),因此它调用它引用的对象的成员(结果)(类型为Area的A1)