継承の詳細
9410 ワード
C++
。 , 。 , 。
, , 。 , 。
is a 。 , , , , , 。
&
, , 。 , 。 , :
class derived-class: access-specifier base-class
, access-specifier public、protected private ,base-class 。 access-specifier, private。
Shape,Rectangle , :
#include <iostream>
using namespace std;
//
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
//
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
//
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
, :
Total area: 35
。 , private。
, :
public protected private
yes yes yes
yes yes no
yes no no
, :
、 。
。
。
, public、protected private 。 access-specifier 。
protected private , public 。 , :
(public): , , , , 。
(protected): , 。
(private): , 。
C++ , :
class derived-class: access baseA, access baseB....
, access public、protected private , , , 。 :
#include <iostream>
using namespace std;
// Shape
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};
//
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
//
cout << "Total area: " << Rect.getArea() << endl;
//
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
, :
Total area: 35
Total paint cost: $2450