avatar
C++ Q96: function inheritance# JobHunting - 待字闺中
c*e
1
Error information in the following code is Error: equals is not a member of
B.
My question: Why equals() is not a member of B but print() is?
While this seems obvious, what is the general rule that a function will be
inherited?
#include
using namespace std;
class A {
public:
bool equal(A a) { return true; }
void print() { cout << "print\n"; }
};
class B: public A {};
int main() {
B b;
bool x = b.equals(b);
b.print();
return 0;
}
avatar
b*c
2
。。。。。
因为equal(A)而不是equal(B),而且b是B啊
avatar
S*I
3
because "equal" is inherited, but "equals" is not.

of

【在 c**********e 的大作中提到】
: Error information in the following code is Error: equals is not a member of
: B.
: My question: Why equals() is not a member of B but print() is?
: While this seems obvious, what is the general rule that a function will be
: inherited?
: #include
: using namespace std;
: class A {
: public:
: bool equal(A a) { return true; }

avatar
b*c
4
哦哦哦,另外一个问题,B不需要显式转换A吗??

【在 S**I 的大作中提到】
: because "equal" is inherited, but "equals" is not.
:
: of

avatar
r*y
5
you defined equal instead of equals

of

【在 c**********e 的大作中提到】
: Error information in the following code is Error: equals is not a member of
: B.
: My question: Why equals() is not a member of B but print() is?
: While this seems obvious, what is the general rule that a function will be
: inherited?
: #include
: using namespace std;
: class A {
: public:
: bool equal(A a) { return true; }

avatar
r*y
6
B will slice down to A

【在 b*****c 的大作中提到】
: 哦哦哦,另外一个问题,B不需要显式转换A吗??
avatar
c*e
7
Faint. I made such a low level mistake. Then what is the output of the
following code?
#include
using namespace std;
class A {
public:
bool equals(A a) { return data==a.data; }
void setData(int input) { data=input; }
private:
int data;
};
class B: public A {};
void main() {
A a;
a.setData(7);
B b;
b.setData(7);
cout << a.equals(b) << endl;
cout << b.equals(a) << endl;
}
avatar
t*n
8
1
1

【在 c**********e 的大作中提到】
: Faint. I made such a low level mistake. Then what is the output of the
: following code?
: #include
: using namespace std;
: class A {
: public:
: bool equals(A a) { return data==a.data; }
: void setData(int input) { data=input; }
: private:
: int data;

avatar
b*c
9
//true
1
1
avatar
f*n
10
确认一下:
cout << a.equals(b) << endl;
比较的是a的data和b.data?
avatar
j*x
11
这还需要确认么

【在 f********n 的大作中提到】
: 确认一下:
: cout << a.equals(b) << endl;
: 比较的是a的data和b.data?

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。