c++ - 调用静态成员函数时出错

标签 c++ static-methods

我在 .h 文件中声明了一个函数,并将 .h 文件包含在我想调用该函数的 .cpp 中,但出现如下错误:

error C2143: syntax error : missing ';' before '.'" or "identifier of (function i'm calling) is undefined

这是示例代码:

帮助.h

class Help
{
public:
    Help(void);
    ~Help(void);

    static int findItems();

};

钱包.cpp

#include "Help.h"

int main()
{
    int choice;
    char ch;

    do{

        cout<<"Please choose an option: \n";
        cout<<"\t1. Locate item. \n";
        cout<<endl;
        cout<<"Your choice: ";
        cin>>choice;


        switch(choice)
        {
             case 1:
                 Help.findItems();//this is the problem
                 break;

我得到错误:

C2143: syntax error : missing ';' before '.'.

如果我改变

static int findItems();

int findItems();

Help.finditems();

findItems();

我得到错误:

identifier "findItems" is undefined. How can i do this properly?

最佳答案

您可以像这样访问函数:

Help::findItems();

或者新建一个Help类的对象,然后写

newObject.findItems();

您编写了 Help.findItems(); 并且出现错误的原因是:

  1. Help 不是对象(可以为其调用函数)

  2. 您没有使用 :: 运算符,这实际上意味着那里的函数未定义。

关于c++ - 调用静态成员函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444308/

相关文章:

c++ - 在 C/C++ 或任何其他此类语言中将 & 符号应用于变量或数据类型时返回什么类型的地址?

c++ - QSqlTableModel 和 DATETIME 列

c++ - 如何定义模板类的 static const 变量

java - 对传递给静态方法的值进行单元测试

Python:如果可能的话,使私有(private)类方法始终静态?

c++ - 如何修改makefile中的库

c++ - 插入集合 vector 时出错

我们可以将一个函数定义为另一个函数吗?

android - 非静态方法问题

java - 子类可以修改 Java 中抽象父类(super class)中静态方法的行为吗?