c**********e 发帖数: 2007 | 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;
} |
b*****c 发帖数: 1103 | 2 。。。。。
因为equal(A)而不是equal(B),而且b是B啊 |
S**I 发帖数: 15689 | 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; }
|
b*****c 发帖数: 1103 | 4 哦哦哦,另外一个问题,B不需要显式转换A吗??
【在 S**I 的大作中提到】 : because "equal" is inherited, but "equals" is not. : : of
|
r*******y 发帖数: 1081 | 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; }
|
r*******y 发帖数: 1081 | 6 B will slice down to A
【在 b*****c 的大作中提到】 : 哦哦哦,另外一个问题,B不需要显式转换A吗??
|
c**********e 发帖数: 2007 | 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;
} |
t*****n 发帖数: 25 | 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;
|
b*****c 发帖数: 1103 | |
f********n 发帖数: 1163 | 10 确认一下:
cout << a.equals(b) << endl;
比较的是a的data和b.data? |
j********x 发帖数: 2330 | 11 这还需要确认么
【在 f********n 的大作中提到】 : 确认一下: : cout << a.equals(b) << endl; : 比较的是a的data和b.data?
|