2015-09-06 202 views
-1

为什么我在输出中获取地址?相反,我应该得到输出长度=(用户输入的值),宽度=(用户输入的值)。 正如在程序主体得到输入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(); 
} 
+1

请不要表现出你的输出(以及构建命令),和你在哪里“得到的地址输出”。你的意思是你在输出中得到了*区*吗? –

+0

你的意思是让'result()'成为'virtual'函数吗? –

+0

你在不同的对象上调用'getdata'和'result'。 – interjay

回答

0

ptr指向类Rectangle(区域类)的孩子的地址,因此它调用的对象是指(户型面积A1)

+1

不,结果是非虚拟的,所以它将在基类上调用。 – interjay

+0

是的,它应该调用基类的结果。 但输出是 长度=一些地址 宽度=一些地址 – Mark

+0

相反,它应该给 长度=(由用户输入值) 宽度=(由用户输入值)我不使用虚拟 – Mark

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(); 
} 
+0

。因此,我期望ptr->结果显示Rectangle类的结果(),而不是区域类 – Mark

+0

的结果(),但是您正在将数据读入到R1中,而您以后不会使用它。在代码中查看我的更新答案以获得解释,如果您发现它有用,请接受我的答案。 – syntagma

+0

@ REACHUS你不应该用你的答案来替换问题。我已经回滚了。 – molbdnilo