我有一个A类:
class A
{
public:
virtual double getValue() = 0;
}
Run Code Online (Sandbox Code Playgroud)
和B级:
class B : public A
{
public:
virtual double getValue() { return 0.0; }
}
Run Code Online (Sandbox Code Playgroud)
然后在main()中我做:
A * var;
var = new B[100];
std::cout << var[0].getValue(); //This works fine
std::cout << var[1].getValue(); //This, or any other index besides 0, causes the program to quit
Run Code Online (Sandbox Code Playgroud)
如果相反,我做:
B * var;
var = new B[100];
std::cout << var[0].getValue(); //This works fine
std::cout << var[1].getValue(); //Everything else works fine too
Run Code Online (Sandbox Code Playgroud)
一切都很好,但好像我的多态性似乎有些不对劲?我很困惑.
以下代码
#include <iostream>
using namespace std;
class A {};
class B : public A {};
class C : public B {};
void foo(A *a) {
cout << 'A' << endl;
}
void foo(B *b) {
cout << 'B' << endl;
}
int main() {
C *c = new C[10];
foo(c);
}
Run Code Online (Sandbox Code Playgroud)
编译好并按预期打印'B'.
但是当我改变main()功能时
int main() {
C c[10];
foo(c);
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误说
test_arr.cpp: In function 'int main()':
test_arr.cpp:23:10: error: call of overloaded 'foo(C [10])' is ambiguous
test_arr.cpp:23:10: note: candidates …Run Code Online (Sandbox Code Playgroud)