相关疑难解决方法(0)

多态性和指向数组的指针

我有一个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)

一切都很好,但好像我的多态性似乎有些不对劲?我很困惑.

c++ arrays polymorphism pointers

7
推荐指数
2
解决办法
5432
查看次数

数组的模糊重载作为指针传递

以下代码

#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)

c++ arrays pointers overloading

1
推荐指数
1
解决办法
204
查看次数

标签 统计

arrays ×2

c++ ×2

pointers ×2

overloading ×1

polymorphism ×1