2013-11-23 24 views
-3

我想在公共類中調用一個無效函數,但我得到的錯誤我不明白:不能在公共類中調用函數...「新類型可能沒有定義在返回類型中」

#include <iostream> 
class Buttons 
{ 
    public: 
     Buttons() 
     { 
      short pushl; 
      short *tail; 
      cout << "Wally Weasel" << "/t"; 
      void init_sub(int x, int y); 
     }; 
     ~Buttons() 
     { 
      cout << "Buttons has been destroyed!"; 
     }; 
} 
int main(int args, char**LOC[]) 
{ 
    int z, a; 
    Buttons::init_sub(z, a); 
    return 2; 
} 
Buttons::void init_sub(int x, int y) 
{ 
    cout << &x << &y; 
} 

最新更新的代碼(仍然不能正常工作):

#include <iostream> 
using namespace std; 

class Buttons 
{ 
    public: 
    Buttons() 
    { 
    short pushl; // unused variable in Constructor: should be a member variable? 
    short *tail; // same 
    cout << "Wally Weasel" << "/t"; 
    }; 

    ~Buttons() 
    { 
    cout << "Buttons has been destroyed!"; 
    } 

void init_sub(int z, int a); 
}; 


int main(int args, char **LOC[]) 
{ 
    int z = 0; 
    int a = 1; 
    Buttons::init_sub(z, a); 
    return 2; 
} 

void Buttons::init_sub(int x, int y) 
{ 
    cout << &x << " " << &y; 
} 

我爲什麼不能調用函數?

原件仍然出錯:

PS「的新類型可能無法在返回類型定義」:我更新了我的代碼以匹配我的情況的現狀 - 儘管仍相同的錯誤。 我一直在努力不懈地用C++ - 我習慣於低層次的編程,而沒有涉及語法/結構的很多語義。

+1

代碼爲 – 2013-11-23 21:34:46

+0

不清楚什麼不清楚呢? –

+1

有一點點混亂,你想做什麼? – 2013-11-23 21:37:25

回答

0

「init_sub」在構造函數中聲明。如果你想通過類本身調用它,它也必須是靜態的。

+0

我更新了,並得到以下錯誤:** t.cpp:在構造函數'Buttons :: Buttons()'中: 第10行:錯誤:'靜態'指定對全局範圍聲明的函數'init_sub'無效 彙編由於嚴重錯誤而終止。** –

1

init_sub函數聲明在錯誤的地方。它必須從構造函數體移到類聲明中。

您不能調用該函數,因爲它是一個非靜態成員函數。它需要一個實例來調用該函數。你沒有提供。要麼在實例上調用它,要麼將其設爲靜態。

您的主要功能也有錯誤的簽名。它應該是

int main(int argc, char* argv[]) 
+0

從未聽過「實例方法」一詞。澄清?我也嘗試過靜態,我仍然無法調用它;請參閱上面的錯誤。 –

+0

與非靜態成員函數相同,但實例方法不太滿意。實例方法不是C++的常用術語。但是,該功能需要一個主題,而您沒有提供。 –

+0

不管怎樣,我的代碼仍然給我相同的原始錯誤。 –

0

我認爲這是你想要做的。請嘗試縮進您的代碼,特別是在向他人尋求幫助時。

編譯版本:http://ideone.com/9lGDvn

#include <iostream> 
using namespace std; 

class Buttons 
{ 
    public: 
    Buttons() 
    { 
    short pushl; // unused variable in Constructor: should be a member variable? 
    short *tail; // same 
    cout << "Wally Weasel" << "\t"; // Corrected tab character 
    }; 

    ~Buttons() 
    { 
    cout << "Buttons has been destroyed!"; 
    } 

    static void init_sub(int z, int a); 
}; 

// Note that second argument to main should be char* loc[], one fewer pointer attribute 
int main(int args, const char* const LOC[]) 
{ 
    int z = 0; 
    int a = 1; 
    Buttons::init_sub(z, a); 
    return 2; 
} 

void Buttons::init_sub(int x, int y) // not "Buttons::void" 
{ 
    cout << &x << " " << &y; 
} 
+0

我仍然得到與上面解釋的相同的原始錯誤。 –

+0

使用複製粘貼,以便您實際運行此代碼。你需要更努力! –

+0

我複製並粘貼了它,但仍然收到相同的錯誤。 @DavidHeffernan你試圖在這裏侮辱我嗎? –

相關問題