exercise.h是如下派生類從兩個相同的派生類
#ifndef EXERCISE_H_
#define EXERCISE_H_
// ROOT namespace
namespace root{
// USHORT definition
typedef unsigned short ushort;
// PI DEFINITION
const double PI = 3.141592;
class shape {
double height;
double width;
public:
shape(double h = 1, double w = 1);
virtual ~shape(){}
double getHeight() const;
double getWidth() const;
virtual double area() const = 0;
};
class rectangle : virtual public shape{
public:
rectangle(double height = 1, double width = 1);
double area() const;
};
class triangle : virtual public shape {
public:
triangle(double h = 1, double w = 1);
double area() const;
};
class someShape : public rectangle, public triangle{
public:
someShape(double rh = 1, double rw = 1, double th = 2, double tw = 2);
double area() const;
double trySomething() const;
};
} // NAMESPACE
#endif /* EXERCISE_H_ */
exercise.cpp是這樣
#include <iostream>
#include <cmath>
#include "exercise.h"
using std::cout;
using std::cin;
using std::endl;
using root::ushort;
// BEGIN SHAPE CLASS
root::shape::shape(double h, double w) : height(h), width(w){
}
double root::shape::getHeight() const{
return this->height;
}
double root::shape::getWidth() const{
return this->width;
}
// END SHAPE CLASS
// BEGIN RECTANGLE CLASS
root::rectangle::rectangle(double h, double w) : shape(h,w){
}
double root::rectangle::area() const{
return this->getHeight() * this->getWidth();
}
// END RECTANGLE CLASS
// BEGIN TRIANGNLE CLASS
root::triangle::triangle(double h, double w) : shape(h,w){
}
double root::triangle::area() const{
return this->getHeight() * this->getWidth()/2;
}
// END TRIANGLE CLASS
root::someShape::someShape(double rh, double rw, double th, double tw) : rectangle(rh,rw), triangle(th,tw){
}
double root::someShape::area() const {
return rectangle::area();
}
double root::someShape::trySomething() const{
return triangle::getHeight() * rectangle::getWidth();
}
和在主
#include <iostream>
#include "exercise.h"
using std::cout;
using std::cin;
using std::endl;
int main(){
root::shape *ptrShape;
ptrShape = new root::someShape(3,2,4,3);
cout << "shape area: " << ptrShape->area() << endl;
delete ptrShape;
}
當我創建一個someShape對象我只獲得了默認值。雖然我啓動派生類。還有另一件事。事實上,我們分別導出矩形和三角形,並從這些對象中派生出另一個對象。編譯器如何決定使用哪個area()函數?
你得到它的輸出?你期望哪些值? –
void root :: someShape :: trySomething()const {三角:: getHeight()<<「三角形:: getWidth()<< endl; \t cout << rectangle :: getHeight()<<「<< << rectangle :: getWidth()<< endl;當我使用這個我得到了 1 1 –