c++ - 继承 - 两个不同 类 中的相同方法名称
c++ - inheritance- the same method name in two different classes
我是 C++
的新人,我可能很容易回答你的问题。
class circle {
protected:
int r;
public:
circle(int re) { r=re; }
double surface() {
return 3.14*r*r;
}
};
class sphere : public circle {
public:
sphere(int r) : circle(r) {}
double surface(){
return 4*3.14*r*r;
}
};
现在,我的问题是如何做类似的事情:创建一个球体对象并使用它来获得圆形而不是球体的表面。当一个被第二个继承时,我可以在两个 类 中以某种方式使用相同的方法名称吗?
您可以通过在其名称前附加 circle::
来访问基础 class' surface
方法:
sphere sph(1);
double s = sph.circle::surface();
你的设计最初是错误的。 Public C++ 中的继承意味着子 是父的一种 特定种类。球体不是圆!
此外,如果你想得到球体的表面积,你应该使你的表面函数virtual
:
class Circle {
public:
virtual double surface();
};
这样,当您在 Sphere
中覆盖它时,将调用 Sphere
版本。
我是 C++
的新人,我可能很容易回答你的问题。
class circle {
protected:
int r;
public:
circle(int re) { r=re; }
double surface() {
return 3.14*r*r;
}
};
class sphere : public circle {
public:
sphere(int r) : circle(r) {}
double surface(){
return 4*3.14*r*r;
}
};
现在,我的问题是如何做类似的事情:创建一个球体对象并使用它来获得圆形而不是球体的表面。当一个被第二个继承时,我可以在两个 类 中以某种方式使用相同的方法名称吗?
您可以通过在其名称前附加 circle::
来访问基础 class' surface
方法:
sphere sph(1);
double s = sph.circle::surface();
你的设计最初是错误的。 Public C++ 中的继承意味着子 是父的一种 特定种类。球体不是圆!
此外,如果你想得到球体的表面积,你应该使你的表面函数virtual
:
class Circle {
public:
virtual double surface();
};
这样,当您在 Sphere
中覆盖它时,将调用 Sphere
版本。