【问题标题】:c++ non-standard syntax; use '&' to create a pointer to member with virtual functionc++ 非标准语法;使用“&”创建指向具有虚函数的成员的指针
【发布时间】:2018-01-20 21:00:01
【问题描述】:
#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);

};

我收到一个错误提示

非标准语法;使用 '&' 在每个 cout 函数上创建一个指向成员的指针。

我没有在虚函数中指定我的int,但是当我尝试它时,它会抛出更多错误!

【问题讨论】:

  • attack 是成员函数的名称。你为什么要把它发送到cout
  • 实际覆盖virtual 函数时会出现什么错误? (例如:void attack(int value))?
  • 我没有在虚拟函数中指定我的 int -- 通过省略 int,这些函数不再是“虚拟的”。

标签: c++ class pointers virtual-functions


【解决方案1】:

派生类中的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';
    }
};

【讨论】:

    【解决方案2】:

    您正在尝试cout attack,这是一个函数的名称。看起来您想将一个整数传递给attack,但它没有参数。

    这是使用参数的外观:

    class tank : public Enemy {
    public: 
        void attack(int i){
            cout << "attack from tank - " << i << endl;
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多