C
Csaba
I have a class which contains an integer acting as a bit map (i.e.
individual bits have separate meanings)
union foo
{
int integer_;
struct{ /* here be bitfields */ } parts_;
foo( int i ) : integer( i ) {}
// various operators here
}
I have implemented operators &= |= ^= as members and operator & | ^ as
nonmembers (as recommeded in More Effective C++).
I'm now wondering how to implement operator~
I can see two possibilities:
1. Member operator:
foo:perator ~() const
{
return foo( ~integer_ );
}
2. Non-member operator:
foo operator ~ ( const foo& f )
{
return foo( f.integer_ );
}
(union behaves like struct: access is public by default, otherwise the
nonmember would have to be a friend).
The two are mutually exclusive; they both do the job. Which one should I
choose ? Which one is better/cleaner/more canonical ?
If I change the data memebrs to private:
union foo
{
private:
int integer_;
struct{ /* here be bitfields */ } parts_;
public:
foo( int i ) : integer( i ) {}
// various operators here
}
then having operator~ as a member is more convenient (no need to declare
it as a friend because it already has access to the private members).
Would that be sufficient reason to choose it ?
individual bits have separate meanings)
union foo
{
int integer_;
struct{ /* here be bitfields */ } parts_;
foo( int i ) : integer( i ) {}
// various operators here
}
I have implemented operators &= |= ^= as members and operator & | ^ as
nonmembers (as recommeded in More Effective C++).
I'm now wondering how to implement operator~
I can see two possibilities:
1. Member operator:
foo:perator ~() const
{
return foo( ~integer_ );
}
2. Non-member operator:
foo operator ~ ( const foo& f )
{
return foo( f.integer_ );
}
(union behaves like struct: access is public by default, otherwise the
nonmember would have to be a friend).
The two are mutually exclusive; they both do the job. Which one should I
choose ? Which one is better/cleaner/more canonical ?
If I change the data memebrs to private:
union foo
{
private:
int integer_;
struct{ /* here be bitfields */ } parts_;
public:
foo( int i ) : integer( i ) {}
// various operators here
}
then having operator~ as a member is more convenient (no need to declare
it as a friend because it already has access to the private members).
Would that be sufficient reason to choose it ?