2013-11-23 25 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你试图在这里侮辱我吗? –

相关问题