#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
class Enemy {
protected:
public :
virtual void attack(int ){
}
};
class tank : public Enemy {
public: void attack( ){
cout << "attack from tank - " << attack << endl;
}
};
class monster : public Enemy {
public:
void attack( ) {
cout << "attack from mob - "<< attack << endl;
};
};
int main() {
tank tnk;
monster mob;
Enemy *enemy1= &tnk;
Enemy *enemy2 = &mob;
enemy1->attack(30);
enemy2->attack(30);
};
我收到错误说
非标准语法;使用'&amp;'在每个cout函数上创建一个指向成员的指针。
我没有在虚拟函数中指定我的int
,但是当我尝试它时,它会引发更多错误!
答案 0 :(得分:3)
派生类中的attack
函数签名与基类虚函数签名不同,因此不覆盖虚拟基础attack
函数。使两个派生类中的函数签名相同,并将参数输出到标准输出:
class tank : public Enemy {
public:
void attack(int n) { // add the int parameter, now overrides
std::cout << "attack from tank - " << n << '\n';
}
};
class monster : public Enemy {
public:
void attack(int n) { // add the int parameter, now overrides
std::cout << "attack from mob - " << n << '\n';
};
};
还要考虑将override说明符添加到两个函数中:
class tank : public Enemy {
public:
void attack(int n) override {
std::cout << "attack from tank - " << n << '\n';
}
};
答案 1 :(得分:2)
您正在尝试cout
attack
,这是一个功能的名称。看起来您想要将整数传递给attack
,但它没有参数。
以下是参数的外观:
class tank : public Enemy {
public:
void attack(int i){
cout << "attack from tank - " << i << endl;
}
};