2012-02-18 2503 views
5

我正在爲我的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" 

兩個ptrAsa->getStyleIdptrAsa->getStyleName

我無法弄清楚這有什麼問題!

回答

15

您在函數調用周圍缺少()。它應該是ptrAsa->getStyleId()

+1

OMG!現在我感到非常愚蠢。多謝你們! OMG! – Kardsen 2012-02-18 17:22:37

6

你缺少在兩個通話括號,它應該是

ptrAsa->getStyleId() 

調用的函數。

ptrAsa->getStyleId 

用於指代成員值/屬性。

+0

OMG!我現在就要爬回我的洞裏。 非常抱歉的愚蠢問題哈哈。 – Kardsen 2012-02-18 17:00:44

+0

適合所有人=) – 2012-02-18 17:03:19

2

您需要調用的功能,不僅引用它:

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