如何在C ++中订购功能? [英] How to order functions in C++?
问题描述
我不知道如何在C ++中订购我的函数。在C中,我只是放置一个函数,使用函数下面的另一个函数,尽可能接近 - 这是很常见的。像这样:
void bar()
{
}
foo()
{
bar();但是,在C ++中,有几种类型的函数:
- 自由功能
- 私人会员功能
- li>
- 静态成员函数
我目前正在使我的函数顺序取决于它们如何排序.hpp文件,例如:
class Foo_bar {
public:
Foo_bar
void foo();
private:
int some_member;
void bar();
但现在,如果构造函数使用foo 源文件中的构造函数,与我通常的顺序不一致。我当然可以重新排序我的标题来考虑:
class Foo_bar {
private:
int some_member;
void bar();
public:
void foo();
Foo_bar();
但我认为这很乱。
此外,在Java中,与我的第一个例子相反的似乎是共同的:
void foo()
{
bar();
}
void bar()
{
}
b $ b
这可能是由于自顶向下的思维常见于OOP,与自下而上的思考在程序/函数编程中常见的相反。但是,对于没有原型的自由函数,这种自上而下的风格是不可能的。
甚至可以以一致的方式在C ++中命令函数?
解决方案这是可能的。您必须使用转发声明。
在定义之前声明一个函数,其他函数即使在之前定义它也不会有问题。
你应该能够在C ++中这样做:
void bar(); // forward declaration;注意,函数bar还没有定义
void foo()
{
bar(); // foo知道bar被声明,所以它将搜索bar的定义
}
void bar()//这里定义bar,所以foo会在需要的时候使用
{
}
I'm not sure how to order my functions in C++. In C, I simply placed a function that uses another function below that function, as closely as possible - that's pretty common. Like this:
void bar()
{
}
void foo()
{
bar();
}
However, in C++, there are several types of functions:
- Free functions
- Private member functions
- Public member functions
- Static member functions
I'm currently making my function order dependent on how they are ordered in the .hpp file, e.g.:
class Foo_bar {
public:
Foo_bar();
void foo();
private:
int some_member;
void bar();
But now, if the constructor uses foo() or bar(), these will be below the constructor in the source file, inconsistent with my usual ordering. I could of course reorder my header to take account of that:
class Foo_bar {
private:
int some_member;
void bar();
public:
void foo();
Foo_bar();
But I think that's a mess.
Furthermore, in Java, the opposite to my first example seems to be common:
void foo()
{
bar();
}
void bar()
{
}
That's probably due to the top-down thinking common in OOP, in contrast to the bottom-up thinking common in procedural/functional programming. However, with free functions that don't have prototypes, this top-down style is not possible.
Is it even possible to order functions in C++ in a consistent way?
解决方案 It's possible. You have to use forward declaration.
Declare a function before defining it, and other functions will see it without problem even if they are defined before.
So, you should be able to do this in C++:
void bar(); // forward declaration; note that function bar isn't defined yet
void foo()
{
bar(); // foo knows that bar is declared, so it will search for bar's definition
}
void bar() // here bar is defined, so foo will use this when needed
{
}
这篇关于如何在C ++中订购功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!