【问题标题】:Error C2446: '==': no conversion from 'int' to 'int (__thiscall keyboard::* )(void)'错误 C2446:“==”:没有从“int”转换为“int (__thiscall keyboard::*)(void)”
【发布时间】:2020-03-03 15:52:37
【问题描述】:

我的代码运行正常,但我在课堂上收到此错误:错误 C2446: '==': no conversion from 'int' to 'int (__thiscall keyboard::* )(void)'。问题来了:

class keyboard {

public:

    char W = 'W';
    char A = 'A';
    char S = 'S';
    char D = 'D';
    char E = 'E';
    char tasta;

    int key_pressed_frd() {
        cin >> tasta;
        if (tasta == W) return 1;
        else return 0;

    }

这是我的课程的一部分,其中包括另外 4 个函数(与这个相同),我得到了同样的错误。

这是我的全部代码:

#include <iostream>

using namespace std;

char tasta;

class keyboard {


public:

    int key_pressed_frd() {
        cin >> tasta;
        if (tasta == 'w') return 1;
        else return 0;

    }

    int key_pressed_back() {
        cin >> tasta;
        if (tasta == 's') return 1;
        else return 0;

    }

    int key_pressed_lft() {
        cin >> tasta;
        if (tasta == 'a') return 1;
        else return 0;

    }

    int key_pressed_rgt() {
        cin >> tasta;
        if (tasta == 'd') return 1;
        else return 0;

    }

    int key_pressed_stop() {
        cin >> tasta;
        if (tasta == 'e') return 1;
        else return 0;

    }
};

void forward() {

    cout << "I go forward!";
}

void back() {
    cout << "I go back!";
}

void left() {
    cout << "I go left!";
}

void right() {
    cout << "I go right!";
}

int main()
{
    //keyboard apas;

    while (true) {

        if (&keyboard::key_pressed_frd == 1)
            while (&keyboard::key_pressed_frd == 1) forward();

        if (&keyboard::key_pressed_back == 1)
            while (&keyboard::key_pressed_back == 1) back();

        if (&keyboard::key_pressed_lft == 1)
            while (&keyboard::key_pressed_lft == 1) left();

        if (&keyboard::key_pressed_rgt == 1)
            while (&keyboard::key_pressed_rgt == 1) right();

        if (&keyboard::key_pressed_stop == 1)
            while (&keyboard::key_pressed_stop == 1) break;

    }
}

它主要使用一个类从键盘获取输入,然后在验证条件时,控制台中会出现一条消息。我认为代码非常错误,因为这是我第一次使用课程,但您的任何帮助将不胜感激!谢谢! PS:在我的语言中,tasta 是指键盘上的随机键

【问题讨论】:

  • 您在此处显示的代码似乎没有表现出您描述的问题。请发布我们可以实际尝试的问题的最小再现。
  • 除此之外,你的代码中有很多奇怪的东西。
  • 您在标题/文本中出现的错误听起来像是您将int 与返回int 的成员函数(指针)进行了比较。会不会是你忘了把()放在成员函数后面(实际调用它)?
  • if (tasta == W) 可以是if (tasta == 'W'),可能不需要char W = 'W'; 及其朋友。
  • 你可以edit你的问题来澄清它。我为你做了。

标签: c++ function class


【解决方案1】:

要调用成员函数,请将空括号附加到它,如下所示:

...
if (keyboard::key_pressed_rgt() == 1)
...

函数名称前的和号,如&amp;keyboard::key_pressed_rgt,告诉编译器获取指向该函数的指针。这不是你需要的。编译器被keyboard::key_pressed_rgt(不带括号)之类的代码弄糊涂了,并建议添加一个&符号。不是个好建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2018-08-23
    • 2018-02-26
    相关资源
    最近更新 更多