C++のクラス内での2次元配列

このQ&Aのポイント
  • C++学習者です。Windows 10上で、Visual Studio Community 2015を使って勉強しています。
  • クラス内で2次元配列を定義しようとするとエラーメッセージが出てきます。
  • 正しい2次元配列の作り方を教えてください。
回答を見る
  • ベストアンサー

C++のクラス内での2次元配列

C++学習者です。Windows 10上で、Visual Studio Community 2015 を使って勉強しています。 2次元配列を持つクラスを作ろうとしていますが、クラス定義ファイルの中のプライベート変数部分に2次元配列を定義しようとするとエラーメッセージが出てきます。 自分のソースコードは次のようなもので、最後の int aray[rowSize][colSize]; の部分に赤い波線が出ていて、そこにカーソルを合わせると「静的でないメンバー参照は特定のオブジェクトを基準とする相対参照である必要があります。」というメッセージが出ます。 #pragma once #ifndef DSUBARRAY_H // Double Subscripted Array #define DSUBARRAY_H #include <iostream> using namespace std; class DsubArray { public: friend ostream &operator<<(ostream &, const DsubArray &); // output array friend istream &operator>>(istream &, DsubArray &); // input array DsubArray(const int=1, const int=1); // default constructor DsubArray(DsubArray &); // copy constructor ~DsubArray(); // destructor int &operator()(int, int);// subscript -- lvalue const int &operator()(int, int) const; // subscript -- rvalue DsubArray &operator=(DsubArray &);// assignment bool operator==(DsubArray &) const; // equality check of the two arrays bool operator!=(DsubArray &) const; // inequality check int getRowSize() const; int getColSize() const; private: int rowSize; int colSize; int aray[rowSize][colSize]; }; #endif これをたとえば次のように書き換えると、赤い波線は消えるのですが、今度はコラムのサイズが10に固定されてしまい、コンストラクターでこれと異なる数値を与えるとエラーになってしまうのではないかと心配します。 int aray[ ][10]; どなたか2次元配列の正しい作り方を教えてください。お願いいたします。

質問者が選んだベストアンサー

  • ベストアンサー
  • wormhole
  • ベストアンサー率28% (1619/5653)
回答No.1

クラスや構造体のメンバ変数として配列を定義する場合はサイズは固定である必要があるのでできません。 ですがポインタを使用して配列ぽく使用する事はできます。

papashiroSooke
質問者

お礼

早速にご回答を頂き、有難うございます。 わかりました。ポインターを要素とする1次元配列を用意して、それを 行とし、列をどのように表現すればよいか、考えてみます。

papashiroSooke
質問者

補足

Row行xCol列個の要素を持つ一次元配列を作り、要素がCol個進むたびにRowを一つ進ませるという形で、疑似的に2次元配列を作りました。 これだとメンバー変数としては行数を表すRow、列数を表すCol 、そして配列のはじめを示す ポインターarrayPtrだけで済みます。 wormholeさんのアドバイスからヒントを得て思いつきました。 有難うございました。

関連するQ&A

  • クラスの作成について

    すみません、クラスの作成について少し教えてください。 以下のようなクラスがあります。 class Vector { public:   //※他、ここにいくつかのメンバ関数がある。   // 入出力   friend istream& operator>>(istream& is, Vector& vector);   friend ostream& operator<<(ostream& os, const Vector& vector); private:   double x;   double y; }; ・・・この// 入出力の istream operator, ostream の具体的な書き方がわかりません。 よかったら教えてください。

  • ポインタの入出力演算子?[C++]

    入出力演算子を使ったコードを書いているのですが わからないところがあるので教えてください。 friend std::ostream& operator <<( std::ostream& out, const Box can ); friend std::istream& operator >>( std::istream& in, Box & can ); friend std::ostream& operator <<( std::ostream& out, const Box * can ); friend std::istream& operator >>( std::istream& ins, Box * & can ); このうち上の二つの普通の演算子はちゃんと動いている のですが、下の二つはどのようにすればいいのかわかりません。 下のコードのようにポインタを使って入出力したいんですが・・・ Box * ptrCan = NULL; cout << ptrCan; ptrCan = &t; cout << ptrCan; cin >> ptrCan; cout << ptrCan;

  • C++での入出力演算子のオーバーロード

    C++学習者です。Visual Studio 2015 を使っています。 入力演算子>> と出力演算子<<をオーバーロードする関数をfriend としてクラス定義の中に書きましたが、”メンバーではありません” というメッセージが出てきてコンパイルできません。 エラー番号はC2039です。 何回調べても原因がわからないので、詳しい方にお聞きしたいです。 どうかよろしくお願いいたします。 ヘッダーファイルと関数定義ファイル、クライアントプログラムと、エラーメッセージのコピーを張り付けてあります。 // クラスヘッダーファイル // class Array header #ifndef ARRAY1_H #define ARRAY1_H #include <iostream> using namespace std; class Array { // operator overloading as non-member functions friend ostream &operator<<(ostream &, const Array &); friend istream &operator>>(istream &, Array &); public: Array(int = 10); // constructor with default of 10 elements of array Array(const Array &); //copy constructor ~Array(); // destructor int getSize() const; // size of array // operator overloadings as member functions const Array &operator=(const Array &); // assignment bool operator==(const Array &) const; // check equality of two arrays // because both sides of the operator are constant, // this function must be constant too bool operator!=(const Array &right) const { // fully defined function in the header file like this one // will be made in-line function and save overhead time return !(*this == right); } int &operator[](int); // check subscript range for non-constant array const int &operator[](int) const; // check subscript range for constant array // remember we can only invoke constant function of a constant object // so if we want to check the subscript range of a constant object, we need // to use a constant member function of that object, that's why we need a // constant version of the same functionn as above operator[] private: int size; // size of array int *ptr; // pointer to the first element of the array // so ptr is the name of the array }; // end of class Array definition #endif // 関数定義ファイル // array1.cpp // member function definitions of class Array #include "stdafx.h" #include <iostream> #include <iomanip> using namespace std; using std::cout; #include <new> // for new and delete #include <cstdlib> // for exit() using std::exit; #include "array1.h" // >> , << 以外のオーバーロード関数は省略します // input operator overloading istream &Array::operator>>(istream &input, Array &a) { for (int i = 0; i < a.size; i++) input >> a.ptr[i]; return input; } // output operator overloading ostream &Array::operator<<(ostream &output, const Array &a) { int i; for (i = 0; i < a.size; i++) { output << setw(12) << a.ptr[i]; if ((i + 1) % 4 == 0) output << endl; } if (i % 4 != 0) output << endl; return output; } // クライアントプログラム // ConsoleApplication87.cpp : コンソール アプリケーションのエントリ ポイントを定義します。 // #include "stdafx.h" #include <iostream> using namespace std; #include "array1.h" int main() { Array integers1(7); // 7 elements array Array integers2; // default 10 element array cout << "size of array integer1 is " << integers1.getSize() << endl; cout << "contents of integers1 after instantiation are :\n"; cout << integers1; cout << "---------------------------------------------\n"; cout << "size of array integers2 is " << integers2.getSize() << endl; cout << "contents of integers2 after instantiation are :\n"; cout << integers2; cout << "---------------------------------------------\n"; return 0; } // エラーメッセージ 1>------ ビルド開始: プロジェクト:ConsoleApplication87, 構成:Debug Win32 ------ 1> array1.cpp 1>c:\users\shiro\documents\visual studio 2015\projects\consoleapplication87\consoleapplication87\array1.cpp(96): error C2039: '>>': 'Array' のメンバーではありません。 1> c:\users\shiro\documents\visual studio 2015\projects\consoleapplication87\consoleapplication87\array1.h(9): note: 'Array' の宣言を確認してください 1>c:\users\shiro\documents\visual studio 2015\projects\consoleapplication87\consoleapplication87\array1.cpp(104): error C2039: '<<': 'Array' のメンバーではありません。 1> c:\users\shiro\documents\visual studio 2015\projects\consoleapplication87\consoleapplication87\array1.h(9): note: 'Array' の宣言を確認してください ========== ビルド: 0 正常終了、1 失敗、0 更新不要、0 スキップ ==========

  • basic_ostreamクラスについて

    http://msdn.microsoft.com/ja-jp/library/k262esc6.aspx をみると、VC++2010のbasic_ostream::sentryには  operator bool( ) const; がある事になっていますが、実際は無いようです。 VC++2010 Express Edition のostream(C:\Program Files\Microsoft Visual Studio 10.0\VC\include\ostream)を見ると、sentryにoperator bool() constがありませんでした。 代わりに __CLR_OR_THIS_CALL _OPERATOR_BOOL() const { // test if stream state okay return (_Ok ? _CONVERTIBLE_TO_TRUE : 0); } というのがありますが、 #define _STD ::std:: #define _OPERATOR_BOOL operator _STD _Bool_type と定義されており、operator bool( ) constとは別物でした。 このため、basic_ostream::sentry::operator bool( )を使用しているソースをVC++2010(Express Edition)でビルドしようとするとエラーになります。 ちなみに、このソースをVC++2008 Express Editionでビルドすると通ります。 質問なのですが、 1)basic_ostream::sentry::operator bool( )を使うソースをVC++2010 Express Editionでビルドするにはどうすれば良いでしょうか? 2)なぜVC++2010 Express Editionからbasic_ostream::sentry::operator bool( )がなくなってしまったのでしょうか? ご存知の方、ご教授ください。 よろしくお願いします。

  • テンプレートクラスのフレンド関数の宣言

    テンプレートクラスに対して、operator << を定義しようとしてハマってしまったので。 ---- 最終的にできたコードはこんな感じ ---- template<size_t M> class MyContainer; template<size_t N> std::ostream& operator<<( std::ostream& os, MyContainer<N> const& cont ); template<size_t M> class MyContainer {  friend   ostream& operator<< <M>( ostream& , MyContainer<M> const& ); <= ここで「operator<<」としてハマった  public:   MyContainer() { }  private:   void Print_( std::ostream& os ) const {    copy( content_, content_ + M, ostream_iterator<int>( os, "\n" ) );   }  private:   int content_[M]; }; template<size_t N> ostream& operator <<( ostream& os, MyContainer<N> const& cont ) {  cont.Print_( os );  return os; } ------------------------------ テンプレートクラスのfriend関数を宣言する場合に、関数に明示的にテンプレート引数を与えないとテンプレート関数の特殊化だけが friend となるようです。 そういうもんだと言ってしまえばそれまでですが、何故こんな変態的な仕様になってるんでしょう? 特殊化された関数だけをテンプレートクラスのfriend に指定したいような状況が想像できません。

  • 2次元配列をConst定義するには?

    2次元配列をConst定義する方法がわからず、困っております。 多次元配列Const定義ができるのかどうかが不安になっております。 ご存知の方がおられましたらご教授いただけないでしょうか。 よろしくお願い致します。 これまでに下記の様な定義をいくつか試みましたが、 コンパイルが通りませんでした。 ・Const XXXXX(5,5) = { {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}}

  • 多次元配列

    初歩的な質問ですみません。 PHPプログラミングでの質問です。 仮に、多次元配列Aに、 Array( [0] => Array ( [0] => 6 ) [1] => Array ( [0] => 2 [1] => 1 ) [2] => Array ( [0] => 0 [1] => 5 [2] => 4 ) ) 多次元配列Bに、 Array( [0] => Array ( [0] => りんご ) [1] => Array ( [0] => ぶどう [1] => パイナップル ) [2] => Array ( [0] => みかん [1] => すいか [2] => メロン ) ) のように値が入っている場合、配列Aの値を参照して 値の大きいものから順に、それに対応する配列Bの値を取り出し、 あたらしい配列Cに代入する処理の書き方を教えて下さい。 上記の例ですと、配列Cが、 Array ( [0] => りんご [1] => すいか [2] => メロン [3] => ぶどう [4] => パイナップル [5] => みかん ) となるようにしたいです。 よろしくお願いします。 長文失礼しました。

    • ベストアンサー
    • PHP
  • テンプレートクラス中のフレンドクラス

    下記をg++(fedora core1)でコンパイルしたところ、 #include <iostream> using namespace std; template< typename T > class A {   T a; public:   A(T aa ) : a(aa) { }   friend ostream& operator<<( ostream &os, const A &a ); //9行目 }; template< typename T > ostream& operator<<( ostream &os, const A<T> &a ) { return os << a.a; } int main( ) {   A<int>  a(5);   cout << a << '\n';   return 0; } 9行目にこのような警告・エラーが出てコンパイルできませんでした。(下記のオプションも試してみましたがダメでした) friend declaration 'std::ostream& operator<<(std::ostream&, const A<T>&)' declares a non-template function (if this is not what you intended, make sure the function template has already been declared and add<> after the function name here) -Wno-non-template-friend disables this warning. :undefined reference to 'operator<<(std::basic_ostream <char, std::char_traits<char> >&, A<int> const&)' なぜ、コンパイルできないのかが分かりません。ちなみに、bcc32(borland c++ compiler5.5.1)では同様のエラーが出てコンパイルできず、cl(VC++6.0)ではコンパイル・実行可能でした。 ご存知の方いらっしゃったらご教授お願いします。(bccとclはWinXPです)

  • 多次元配列のソートがうまくいかない

    多次元配列のソートがうまくいかない 質問失礼します. 以下のような,String型,int型,double型の混在した多次元配列([3][3]の配列)をソートするプログラムを作成しました. このプログラムでは3番目の項目でソートを行っています. 問題点なのですが, 3番目の項目がdouble型の一桁(例えばarray[1][2]が2.0)ならばうまくソートできるのですが, 一つを2桁(例えばarray[1][2]を10.0)にすると何故か先頭の数(10.0の場合1)を基準にソートされてしまっているようです・・・ 配列へのデータの入れ方が間違っているのでしょうか? 原因がはっきりわからず困っているのですが, わかる方いましたらよろしくお願いします. public class Sort_test { /** * @param args */ public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ String[][] array = new String[3][3]; array[ 0 ][ 0 ] = "A"; array[ 0 ][ 1 ] = 2001+""; array[ 0 ][ 2 ] = 9.0+""; array[ 1 ][ 0 ] = "B"; array[ 1 ][ 1 ] = 1001+""; array[ 1 ][ 2 ] = 2.0+""; array[ 2 ][ 0 ] = "C"; array[ 2 ][ 1 ] = 3001+""; array[ 2 ][ 2 ] = 6.0+""; TheComparator comparator = new TheComparator(); // 3番目の項目でソートするように設定 comparator.setIndex( 2 ); // ソート実施 Arrays.sort( array, comparator ); dump(array); } public static void dump( String[][] array ) { for ( int i = 0;i < array.length;i++ ) { for ( int j = 0; j < array[ i ].length;j++ ) { System.out.print( "\t" + array[ i ][ j ] ); } System.out.println(); } } } //多次元配列ソート用クラス class TheComparator implements Comparator { /** ソート対象のカラムの位置 */ private int index = 0; /** ソートするためのカラム位置をセット */ public void setIndex( int index ) { this.index = index; } public int compare( Object a, Object b ) { String[] strA = ( String[] ) a; String[] strB = ( String[] ) b; return ( strA[ index ].compareTo( strB[ index ] ) ); } }

    • ベストアンサー
    • Java
  • 多次元配列の重複削除

    PHPの多次元配列の重複削除で悩んでいます・・・。 例) array(4) { [0]=> array(2) { ["name"]=>string(10) "春" ["cool"]=>int(0) } [1]=> array(2) { ["name"]=>string(14) "冬" ["cool"]=>int(200) } [2]=> array(2) { ["name"]=>string(14) "冬" ["cool"]=>int(0) } [3]=> array(2) { ["name"]=>string(14) "冬" ["cool"]=>int(200) } } 上記のような配列があった場合 下記のように重複してるものを削除させたいのです・・・。 array(4) { [0]=> array(2) { ["name"]=>string(10) "春" ["cool"]=>int(0) } [1]=> array(2) { ["name"]=>string(14) "冬" ["cool"]=>int(200) } [2]=> array(2) { ["name"]=>string(14) "冬" ["cool"]=>int(0) } } array_unique($array)を使用してもうまく行かず 悩んでおります。。。。 よい方法等あればご教授お願いいたします。

    • ベストアンサー
    • PHP