Ata*_*xia 14 c++ oop coding-style
在C++中为类编写辅助方法时,是否应该在标题(.h)文件的类定义中将其声明为私有方法?例如:
/*Foo.h*/
class Foo {
public:
int bar();
private:
int helper();
};
...
/*Foo.cpp*/
...
int foo::bar() {
int something = this->helper();
}
int foo::helper() {
...
}
Run Code Online (Sandbox Code Playgroud)
或者,最好不要将它声明为类的私有成员,而只是使它成为实现中的独立函数?
/*Foo.h*/
class Foo {
public:
int bar();
};
...
/*Foo.cpp*/
...
int Foo::bar() {
int something = helper();
...
}
int helper() {
...
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 21
实现文件中的一个独立函数改进了封装:它不需要在头文件中声明,因此当签名因任何原因发生更改时,不会重新编译客户端代码.对我来说,这是一个足够好的理由,只要可行,就更喜欢这个选项.(务必将其放在匿名命名空间中以防止链接时发生标识符冲突.)
但是,private方法可以通过指针访问类实例及其私有部分this.如果它需要这样的访问,那么它必须是一个方法或一个friend.在这两种情况下,它都会在类定义(头文件)中可见,并且方法比朋友更方便.