0

唯一のコンストラクターが整数を受け入れるクラスがあり、それをポインターにせずに新しい/削除を使用せずに別のクラスで使用したいと考えています。

これは可能ですか?

ファーストクラスの関連部分:

class A
{
  private:
  int size; 
  char *c;

  public:
  A(int i)
  {
    size = i;
    c = new char[i];
  }
  ~A() { delete[] c; }
}

そして、次のようにクラス B の例で使用したいと思います。

class B
{
  private:
  A a(7); // Declaration attempt #1
  A b; //Declaration attempt #2
  A *c; //This is what I'll do if I have no other choice.

  public:
  B()
  {
    b = A(7); //Declaration attempt #2
    c = new A(7);
  }
}
4

1 に答える 1

4

関数宣言として解釈されるため、使用するオブジェクトのクラス内初期化()はできません。代わりに member-initializer リストを使用してこれを行うことができます。

class B
{
    A a;

    public:
        B() : a(7)
    //      ^^^^^^
        {}
};

これはコンストラクター内の割り当てでも機能しますが、割り当ての代わりに初期化するため、メンバー初期化リストをお勧めします。

C++11 では、uniform-initialization を使用できます。

class B
{
    A a{7};                                                                    /*
    ^^^^^^^                                                                    */

    public:
        B() = default;
};
于 2013-06-13T00:36:42.203 に答える