c++ - 没有可行的重载 '=' 和继承

标签 c++ eclipse inheritance reference

我有以下类结构,但是当我构建时,我不断收到错误:

error: no viable overloaded '='
                        p1 = new HumanPlayer();
                        ~~ ^ ~~~~~~~~~~~~~~~~~
../Test.cpp:14:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'HumanPlayer *' to 'const Player' for 1st argument; dereference the argument with *
class Player {
      ^
1 error generated.
class Player {
public:
    void getMove(int player) {
        cout << "Get move" << endl;
    }
};

class HumanPlayer: public Player {
public:
    void getMove(int player) {
        cout << "Get Human move \n";
    }
};

class MyClass {
public:
    int mode;
    Player p1;

    MyClass() {
        mode = 0;
        cout << "Choose a mode: \n";
        cin >> mode;
        switch (mode) {
            case 1:
            p1 = new HumanPlayer();
            break;
            default:
            break;
        }
        p1.getMove(0);
    }
};

int main() {
    MyClass c;
    return 0;
}

我尝试将 Player p1; 更改为 Player* p1; 并将 p1.getMove 更改为 p1->getMove 但随后它无法正常工作。它打印了 Get move 而不是 Get Human move

最佳答案

如上所述

p1 = new HumanPlayer();

如果 p1 被声明为指针,则有效,与 java 不同,您可以在 c++ 中使用或不使用 new 关键字进行赋值...

在您的情况下,将 p1 声明为指针就可以了

Player* p1{nullptr};
 

及以后

p1 = new HumanPlayer();

关于c++ - 没有可行的重载 '=' 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69103714/

相关文章:

c++ -::在C++中是什么意思?

windows - Hadoop WordCount 示例

eclipse - m2eclipse:Eclipse 在 JRE 中运行,但需要 JDK

c++ - gcc 链接错误 : undefined reference to symbol '_ZN2cv5flann12SearchParamsC1Eifb' ,

c# - 从抽象父类调用泛型列表上的方法

c++ - 为什么我得到 "non-aggregate cannot be initialized with initializer list"

c++ - 使用 fscanf() 解析忽略空格或缺失值?

c++ - 删除 char 数组似乎根本不会影响数组

c++ - 如何更改子类方法中的参数?

c++ - 从纯抽象基类继承 typedef