指向绑定函数的指针只能用于调用该函数

A pointer to a bound function may only be used to call the function

本文关键字:函数 用于 调用 指针 绑定      更新时间:2023-10-16

我正在为我的C++类做家庭作业,遇到了一个问题,我无法弄清楚我做错了什么。

需要注意的是,文件的分离是必要的,我意识到如果我只是在main中创建一个结构AttackStyles,并完全放弃额外的类文件,这会容易得多。

我的问题的基础是,我似乎无法循环遍历一组类并提取基本数据。这是代码:

// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
    int styleId;
    string styleName;
public:
    // Constructors
    AttackStyles();  // default
    AttackStyles(int, string);
    // Destructor
    ~AttackStyles();
    // Mutators
    void setStyleId(int);
    void setStyleName(string);  
    // Accessors
    int getStyleId();
    string getStyleName();  
    // Functions
};
#endif

/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;

// Default Constructor
AttackStyles::AttackStyles()    
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
    setStyleId(i);
    setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()    
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
    styleId = i;
}
void AttackStyles::setStyleName(string n)
{
    styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
    return styleId;
}
string AttackStyles::getStyleName()
{
    return styleName;
}

//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
    const int STYLE_COUNT = 3;
    AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"), 
                                     AttackStyles(2, "Second"), 
                                     AttackStyles(3, "Third")};
    // Pointer for the array
    AttackStyles *ptrAsa = asa;
    for (int i = 0; i <= 2; i++)
    {
        cout << "Style Id:t" << ptrAsa->getStyleId << endl;
        cout << "Style Name:t" << ptrAsa->getStyleName << endl;
        ptrAsa++;
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

我的问题是为什么我会得到错误:

  "a pointer to a bound function may only be used to call the function"

在CCD_ 3和CCD_?

我搞不明白这是怎么回事!

函数调用中缺少()。应该是ptrAsa->getStyleId()

两个调用都缺少括号,应该是

ptrAsa->getStyleId() 

调用函数。

ptrAsa->getStyleId 

用于引用成员值/属性。

您需要调用函数,而不仅仅是引用它:

    std::cout << "Style Id:t" << ptrAsa->getStyleId() << "n";
    std::cout << "Style Name:t" << ptrAsa->getStyleName() << "n";

在使用箭头运算符调用函数(ptrAsa->getStyleId)时,忘记将()放在最后。