假设这种情况:
A.h
class A{
private:
int a;
//...
int a_function();
};
A.cpp
static void helper(A * this_){
// need to do stuff with this_->a
}
int A::a_function(){
helper(this);
}
我们的想法是拥有这个helper函数,它的唯一目的是分解a_function
,使代码更可读。它不应该在.o中导出(像通常的静态函数一样(。
但是,如何使它能够访问私有成员(以可读的方式,无需指针破解(?
(理想的情况是将其作为成员函数,但我认为这更不可能…(
您可以将helper()
声明为friend
:
//A.h
class A {
private:
int a;
//...
int a_function();
friend void helper(A* this_);
};
//A.cpp
static void helper(A* this_) {
this_->a;
}
int A::a_function() {
helper(this);
}
有关更多信息,请参阅https://www.cplusplus.com/doc/tutorial/inheritance/或https://en.cppreference.com/w/cpp/language/friend.
考虑使用非成员、非友元函数。它们通过接口强制访问数据类型,并使类的使用变得更容易,而不正确地使用它则更困难。
//A.hpp
class A{
//If these are only return/assignment expressions,
//consider making the member variable public.
int GetA() const noexcept;
void SetA(int newA) noexcept;
private:
int a;
//...
};
//A.cpp
static int helper(A& a){
//Example usage...
//a.GetA();
//...
//int newA{};
//a.SetA(newA);
//return newA;
}