C++structとclassの違い

1669 ワード

1 struct継承
最近HIDLを分析して、HIDLの生成の中でgoogleは大量のstruct継承を使って、例えば
struct BnHwLight : public ::android::hidl::base::V1_0::BnHwBase 

まずstructとclassの継承面での相違点1 struct defaults to public access and class defaults to private accessを見てみましょう.2 When inheriting, struct defaults to public inheritance and class defaults to privateinheritance. (Ironically, as with so many things in C++, the default is backwards: publicinheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public"keyword. 上の2つの違いからstructのデフォルトはpublic継承であり、メンバーのデフォルトはpublicである.なぜグーグルはstructクラス継承を使うのですか?一つの原因はstructデフォルトpublic継承であり、HIDLのインタフェースはプログラムによって自動的に生成され、自動化の利便性のために、すべてのメンバーがデフォルトpublicであり、外部呼び出しが便利であると思います.
二explicitキーワード使用
同時にHIDLで生成されたstructクラスでは、コンストラクション関数は次のように宣言されます.
    explicit BnHwLight(const ::android::sp &_hidl_impl);

次の例を見てください
class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }
  int GetFoo () { return m_foo; }
private:
  int m_foo;
};
void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}
int main ()
{
  DoBar (42);
}

mainではDoBarのパラメータはFooクラスではなくIntタイプであるが,FooクラスにはintをFooに変換するコンストラクタがあるため,コンパイラはFooのコンストラクタを用いて42をパラメータとしてFooクラスに変換する.Fooのコンストラクション関数をexplicitと定義すると、コンパイルフェーズでエラーが発生します.このような暗黙的な変換によるBUGを回避するためにexplicitを追加します.例えば、MyString(int size)クラスとコンストラクション関数があり、同時に関数print(const MyString&)があり、print(3)を呼び出すとexplicitを使用しないと、出力3ではなく3つの空文字のstringがデフォルトで出力されます.hidl_genでexplicitを使うのもコードが自動的に生成されるため、暗黙的な変換でBUGが存在する可能性があります.