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



我有以下类结构,但当我构建时,我一直得到错误:

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声明为指针将是ok

Player* p1{nullptr};

p1 = new HumanPlayer();

最新更新