我一直在为考试学习 C++,我以为我已经理解了大部分 C++ 常见的误解,但我在过去的考试中遇到了一个让我发疯的练习,它以某种方式结合了虚拟方法和继承我似乎不明白这里是代码:
#include <iostream>
class B;
class A {
public:
virtual A* set(A* a) = 0;
};
class B : public A {
public:
virtual A* set(B* b) {
std::cout << "set1 has been called" << std::endl;
b = this;
return b;
}
virtual B* set(A* a) {
std::cout << "set2 has been called" << std::endl;
a = this;
return this;
}
};
int main(int argc, char *argv[]) {
B *b = new B();
A *a = b->set(b);
a = b->set(a);
a = a->set(b);
a = a->set(a);
return 0;
}
输出是
set1 has been called
set2 has been called
set2 has been called
set2 has been called
从我收集到的第一个调用 (b->set(b) ) 调用 B 类的第一个方法并返回 b 本身,然后这个 objectref 被强制转换为 A 意味着现在对象 b 现在是 A 类型?所以我有 A *a = A *b; 现在对我来说应该调用 A 集是有意义的,因为我脑子里有这种情况,
objectoftypeA->set(objectoftypeA)
所以我不应该研究虚拟方法,因为这两个对象是基类?
无论如何,正如您所看到的,我有很多困惑,所以如果我犯了愚蠢的错误,请多多包涵.