在 C++ 中为类编写辅助方法时,是否应在头文件 (.h) 中的类定义中将其声明为私有(private)方法?例如:
/*Foo.h*/
class Foo {
public:
int bar();
private:
int helper();
};
...
/*Foo.cpp*/
...
int foo::bar() {
int something = this->helper();
}
int foo::helper() {
...
}
或者,最好不要将其声明为类的私有(private)成员,而是将其设为实现中的独立函数?
/*Foo.h*/
class Foo {
public:
int bar();
};
...
/*Foo.cpp*/
...
int Foo::bar() {
int something = helper();
...
}
int helper() {
...
}
最佳答案
实现文件中的独立函数改进了封装:它不需要在 header 中声明,因此无论出于何种原因,当其签名发生更改时,都无需重新编译客户端代码。对我来说,这是一个足够好的理由在可行的情况下更喜欢这个选项。 (请务必将其放在匿名命名空间中,以防止链接时标识符冲突。)
但是,private
方法可以通过 this
指针访问类实例及其私有(private)部分。如果它需要这样的访问,那么它必须是方法或 friend
。在这两种情况下,它都会在类定义(头文件)中可见,并且方法比 friend 更方便。
关于c++ - 辅助函数应该放在头文件中还是放在实现文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737203/