-1
C++で動的に割り当てられたテーブルクラスの '< <'演算子のオーバーロード時に問題があります。ここでC++のフレンド関数からプライベートメンバーにアクセスする際のエラー
は、ヘッダファイルです:
#ifndef INT_TABLE_H
#define INT_TABLE_H
#include<cstdlib>
#include<iostream>
class Table {
public:
Table();
Table(int n);
Table(const Table& orig);
virtual ~Table();
friend std::ostream& operator<<(std::ostream& out, const Table& t);
private:
int** table;
int rows;
int cols;
};
#endif /* INT_TABLE_H */
そして、ここでは、問題の関数である。
std::ostream& operator<<(std::ostream& out, const Table& t)
{
for(int i=0;i<t.rows;i++)
{
for(int j=0; j<t.cols; j++)
{
std::cout<<"["<<"."<<"]";
}
std::cout<<std::endl;
}
}
私は、コードを実行すると、私は次のような出力が得られます。
1 [main] algproject1 6360 cygwin_exception::open_stackdumpfile: Dumping stack trace to algproject1.exe.stackdump
this is a table
[.][.][.][.][.]
[.][.][.][.][.]
[.][.][.][.][.]
[.][.][.][.][.]
[.][.][.][.][.]
RUN FAILED (exit value 35,584, total time: 1s)
テーブルはまだ印刷されますが、上記のエラーが発生します。 私は、t.rowsとt.colsを数字(たとえば5)に置き換えると、問題なく正しく動作することを発見しました。問題が何であるかについて誰かが洞察力を持っていますか?ダイナミックメモリの割り当ては私にとっては比較的新しい概念です。
別の簡単な質問ですが、印刷のためにテーブルの要素にどのようにアクセスすればよいですか?私が "。" t [0] [0]を入力すると、次のエラーが表示されます。
int_table.cpp: In function 'std::ostream& operator<<(std::ostream&, const Table&)':
int_table.cpp:50:34: error: no match for 'operator[]' (operand types are 'const Table' and 'int')
std::cout<<"["<<t[0][0]<<"]";
^
ご提供いただけるヘルプや説明は非常に高く評価されています。
'class Table'には' operator [] 'がありません。あなたは 't.table [0] [0]'を意味しましたか? – Oktalist
うわー。私の非常に愚か。ありがとうございました。 最初の部分はどうですか? –
いいえ、表示されていないコードの部分に問題があります。 – Oktalist