没有可行的重载 '=' 和继承
no viable overloaded '=' and inheritance
我有以下 class 结构,但在构建时,我不断收到错误消息:
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();
我有以下 class 结构,但在构建时,我不断收到错误消息:
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();