C++;不同格式的函数 当你在C++中声明一个方法时,你会这样做,例如如下(如果类名是Lexer):

C++;不同格式的函数 当你在C++中声明一个方法时,你会这样做,例如如下(如果类名是Lexer):,c++,function,C++,Function,或 由于我使用了第一种样式,但我发现最后一种样式也在本网站中使用:如下所示: struct Lexer { bool IsDigit() { return true; } // ... }; struct Lexer { bool IsDigit(); // ... }; bool Lexer::IsDigit() { return true; } 或者像这样: struct Lexer { bool IsDigit() { return true;

由于我使用了第一种样式,但我发现最后一种样式也在本网站中使用:

如下所示:

struct Lexer
{
    bool IsDigit() { return true; }
    // ...
};
struct Lexer
{
    bool IsDigit();
    // ...
};

bool Lexer::IsDigit() { return true; }
或者像这样:

struct Lexer
{
    bool IsDigit() { return true; }
    // ...
};
struct Lexer
{
    bool IsDigit();
    // ...
};

bool Lexer::IsDigit() { return true; }

第一个版本包括类定义中的成员函数定义。后者只将成员函数声明放在类定义内,而将成员函数定义放在类定义外(或“线外”)。

第二个示例是

a) 独立功能或
b) 内联方法定义(如果它在类主体内)

第一个示例是外部方法定义

class Lexer {
    bool IsDigit(); // method declaration
}
bool Lexer :: IsDigit() { return false; } // method definition

bool IsDigit() { return false; } // free-standing function 

class Lexer2{
    bool IsDigit { return false; } // inline method definition
}
他们可以这样称呼:

Lexer l;
l.isDigit(); // calls the first method
isDigit(); // calls the free-standing function
Lexer2 l2;
l2.IsDigit(); // calls the latter method

您是否混淆了声明、定义和内联定义?不。他只是对自由函数一无所知,我猜你是来自Java吗?C++有两种(免费)功能和方法,它们是定义,而不是声明。如果阅读该教程中的文本,您可能会注意到它没有提到类或方法(或成员函数,因为在C++中通常调用方法)。这是有原因的。我建议你买一本好书。选民能解释一下为什么吗?你为什么认为这是错的?我故意省略了返回语句,因为这不是这个答案的内容。如果你认为它们在问题的上下文中是至关重要的,只需在中编辑它们。或者你的意思是因为它是私有的?这不是一个SSCCE,这只是为了显示问题中所问的函数的“格式”。顺便说一句,任何带有
-Wno返回类型的主要编译器都可以编译代码,其中没有显式return语句的bool函数会产生false。我不是因为互联网的原因而争论的,但因为我认为没有必要抱怨某些事情,所以答案显然不是关于这些。就像我说的,如果你认为它很重要,就把它编辑进去。这就是为什么每个人都可以编辑答案。