C++のconstについて

このQ&Aのポイント
  • C++のconstキーワードについて質問です。
  • 具体的には、何時にconstを定義するべきかと、なぜconstが必要なのかについて教えてください。
  • また、コードの中に現れる(!!!!)や(????)についても理解しておきたいです。
回答を見る
  • ベストアンサー

constについて

#include <iostream> using namespace std; class I { int *x; public: unsigned int size; I(){size=0;x=new int[size];} I(unsigned int i){size=i;x=new int[size];} ~I(){delete []x;} int &operator()(unsigned int i){return x[i];}//!!!! const int &operator()(unsigned int i) const{return x[i];}//???? }; void main() { I a(10); for(int i=0;i<10;i++)a(i)=i;a(2)=a(0); for(int i=0;i<10;i++)cout<<a(i); } この場合は//????はいらないと思いますが //????を定義することがありますがどんな場合でしょう //!!!!があるのにあったほうがいいのはどんな場合でしょう?

  • nubou
  • お礼率62% (293/470)

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

  • ベストアンサー
回答No.2

> 厳密な型宣言のため > const int &operator()(unsigned int i) const{return x[i];}//???? > の中の後ろのconstはいると思うのですが > 前のconstはいるのでしょうか? なかったらとてもヤバいことがおこります。 const I a(5); a(1) = 3; // a は const のはずなのに、中身が書き換わる!! >> 大抵の参考書に書いてあると思うがなぁ: > なにせまだ規格が流動的でSTLが規格になっていないときの本なのでだいぶ抜けているのです ならば参考書買い替えの時期では? それにこの件に関する限り、STLとは何の関係もありません。

nubou
質問者

お礼

確認しました STLについては古いことを説明するために出したもので他意はありません ありがとうございました

その他の回答 (1)

回答No.1

> //????を定義することがありますがどんな場合でしょう const I a; に対し a(i) したいとき。 > //!!!!があるのにあったほうがいいのはどんな場合でしょう? a(i)に対して代入することで、a.x[i]を書き換えたいとき。 # 大抵の参考書に書いてあると思うがなぁ...

nubou
質問者

補足

厳密な型宣言のため const int &operator()(unsigned int i) const{return x[i];}//???? の中の後ろのconstはいると思うのですが 前のconstはいるのでしょうか? 大抵の参考書に書いてあると思うがなぁ: なにせまだ規格が流動的でSTLが規格になっていないときの本なのでだいぶ抜けているのです 説明を簡単時するために最小限の記述にしましたが下が全体像です sizeを変更できないようにpribateにしてgetsize()なる関数を定義すべきですが・・・・ #include <iostream> using namespace std; class I { int *x; public: int size; I(){size=0;x=new int[size];} I(int i){size=i;x=new int[size];} I(const I &a) { if(size)delete []x;size=a.size;x=new int[size]; for(int i=0;i<size;i++)x[i]=a(i); } ~I(){delete []x;} I &operator=(const I &a) { if(size)delete []x;size=a.size;x=new int[size]; for(int i=0;i<size;i++)x[i]=a(i);return *this; } int &operator()(int i){return x[i];}//!!!! const int &operator()(int i) const{return x[i];}//???? }; ostream &operator<<(ostream &cout,const I &a) {for(int i=0;i<a.size;i++)cout<<a(i);cout<<"\n";return cout;} void main() { I a(10),b,c; for(int i=0;i<a.size;i++)a(i)=i;a(2)=a(0); cout<<a<<b<<c;cout<<a;c=b=a;cout<<a<<b<<c; }

関連するQ&A

  • 参照について

    C++初心者です。 #include <iostream> using namespace std; class Foo{ public: Foo() {;} Foo(const Foo&) {cout<< "A ";} Foo& operator = (const Foo&){cout << "B "; return *this;}   ←← }; int main(){ Foo x; x = Foo(); return 0; } において←←の部分を上記のようにFoo& operatorにした場合には 出力が"B"となりFoo operatorにした場合には出力が"B A"になりました。&がある場合と無い場合でどのようなことが起こっているのかよく分からないのですが教えて頂けないでしょうか? よろしくお願いします。

  • const 回りのエラー?

    以下のプログラムをcygiwn 上でコンパイルすると エラーが出るのですが 何がいけないのかよくわかりません。 メッセージを読んでconst 回りなのかな?とは思っているのですが… よろしくお願いします。 #include<iostream> #include<cstring> #include<cstdlib> using namespace std; class sample{ char *s; public: sample(); sample(const sample &ob); ~sample(){if(s) delete [] s; cout << "Freeing s\n";} void show(){cout << s << "\n";} void set(char *str); sample operator=(sample &ob); }; sample::sample() { s = new char('\0'); if(!s){ cout << "Allocation error\n"; exit(1); } } sample::sample(const sample &ob) { s = new char[strlen(ob.s)+1]; if(!s){ cout << "Allocation error\n"; exit(1); } strcpy(s,ob.s); } void sample::set(char *str) { s = new char[strlen(str)+1]; if(!s){ cout << "Allocation error\n"; exit(1); } strcpy(s,str); } sample sample::operator=(sample &ob) { if(strlen(ob.s)>strlen(s)){ delete [] s; s = new char[strlen(ob.s)+1]; if(!s){ cout << "Allocation error\n"; exit(1); } } strcpy(s,ob.s); return *this; } sample input() { char instr[80]; sample str; cout << "Enter a string: "; cin >> instr; str.set(instr); return str; } int main() { sample ob; ob = input(); ob.show(); return 0; } <コンパイル結果> In function 'int main()': 78:error:no match for 'operator=' in 'ob = input()()' 49:note:candidates are: sample sample::operator=(sample&)

  • 教えてください

    #include<iostream> using namespace std; int main() { int i; double a[5]; for(i = 0; i < 5; i++){ a[i] = 0.0; } for(i = 0; i < 5; i++) cout << "a[" << i << "] = " << a[i] << "\n"; return 0; } どこが違うんでしょうか? 出力を0.0にしたいんですけど ならないので教えてください。

  • C++画像処理に困っています。。

    #include<iostream> #include<fstream> using namespace std; int main() { char outfile[]="256x256x100.bin";     ifstream fin(outfile, ios::in| ios::binary); ofstream fout; if(!fin){ cout << "ファイル1はオープンできません。endl"; return 1; } } const int SIZE=256; const int SLICE=100; signed short int* matrix= new signed short int[(SIZE)*(SIZE)*(SLICE)]; for(int i=0; i<SIZE*SIZE*SLICE; i++){ fin.read((char*) &matrix[i],sizeof(signed short int)); cout << matrix[i]; } delete[] matrix; fin.close(); fout.close(); return 0; } 上のように256x256x100の三次元データ(XxYxZ)を読み込む事ができ、256 pixelx256 pixelの画像が100枚表示することが出来ました。 次に、その画像データをXZ軸方面から見た画像データにしたいのですが、どのようにすればいいのでしょうか? たぶんY方向のデータを足し算して平均を求めればよいとは思うのですが、 プログラミング初心者なので、処理の方法が全く思い浮かびません。 どなたか教えて頂けますでしょうか?

  • vectorを使用したときのクラス定義について

    現在C++で、STLのvectorを学習しているのですが、 本を見ると ベクトルに保存されるクラスオブジェクトについて 「"<" および "=="を定義する必要がある」 っと書いてあります。 実際のサンプルなどでは、(長くなってしまってすみません) // ベクトルにクラスオブジェクトを保存する #include <iostream> #include <vector> using namespace std; class Demo { double d; public: Demo() { d = 0.0; } Demo(double x) { d = x; } Demo &operator=(double x) { d = x; return *this; } double getd() { return d; } }; bool operator<(Demo a, Demo b) { return a.getd() < b.getd(); } bool operator==(Demo a, Demo b) { return a.getd() == b.getd(); } int main() { vector<Demo> v; int i; for(i=0; i<10; i++) v.push_back(Demo(i/3.0)); for(i=0; i<v.size(); i++) cout << v[i].getd() << ' '; cout << endl; for(i=0; i<v.size(); i++) v[i] = v[i] .getd() * 2.1; for(i=0; i<v.size(); i++) cout << v[i].getd() << ' '; cout << endl; return 0; } っというように書かれています。 ここで、なぜ<や==演算子をオーバーロードする必要があるのかが わかりません。 VC6.0やbccコンパイラで、演算子のオーバーロード箇所をコメントにしても通ってしまいます。 また、本には、「コンパイラによってはその他の比較演算子の定義も必須とされています」っとあります。 お手数おかけしますが、この辺りのことを簡単に(初心者なので・・・)教えていただけたら。と思います。 よろしくお願いします。

  • C++ ソートのやり方

    僕が作ったプログラムで、これはバブルソートなのかわからないので教えてください。 また、ほかのソートの仕方も教えてください。 よろしくお願いします。 汎用関数を使っているのでわかりにくいかもしれないですがお願いします。 #include <iostream> using namespace std; template <class X>void Sort(X *data, int size) { X temp; for (int i = 0; i < size; i++){ for (int j = i + 1; j < size; j++){ if (data[i]>data[j]){ temp = data[i]; data[i] = data[j]; data[j] = temp; } } } } int main() { int i[10]{1, 4, 3, 5, 2, 10, 2, 7, 6, 8}; char c[10]{'c', 'b', 'z', 'a', 'x', 'y', 'j', 'n', 'm', 'r'}; Sort(c, 10); Sort(i, 10); for (int j = 0; j < 10; j++){ cout << i[j] << ' '; } cout << endl; for (int j = 0; j < 10; j++){ cout << c[j] << ' '; } cout << endl; getchar(); return 0; }

  • 関数呼び出しについて

    今cygwin 上でC++の勉強をしているのですが 以下の2つのプログラムの違いがよくわかりません どなたかよろしくお願いします <プログラム1> #include<iostream> using namespace std; int a(); int main(){ cout << abs();  return 0;} int a(){ cout << "test\n";  return 1;} <プログラム2> #include<iostream> using namespace std; int a(int i); int main(){ cout << a(1);  return 0;} int a(int i){ cout << "test\n";  return i;} プログラム1では関数a()内の"test"が出力されるのですが プログラム2ではa(int i)内の"test"は出力されません。 この違いはどこにあるのでしょうか? 同じプログラムでint a() と int a(int i)を double a() と double a(double d)にすると この違いは生じません。なぜaの戻り値をint に設定したときだけ この違いが生じるのでしょうか?

  • 配列の要素

    #include <iostream> using namespace std; int main() { int n[10] ={1,2,3,4,5,6,7,8,9,10}; int i; for(i = 0; i < 10; i++){ cout << "a[" << i << "] = " << n[i] << endl; } return 0; } ここまでは完成することはできたのですが この要素の並びをシャッフルしてランダムな順に並び変える方法がわかりません。

  • C++の配列について

    #include <iostream> using namespace std; int main() { float w[] = {1.2,2.3,3.4,4.5,5.6}; float x[] = {4.8,2.6,1.3,9.1,8.7}; float u = 0.0; int i; for(i=0;i<5;i=i++) { u += w[i] * x[i]; } cout << "u=" << u << "です\n"; return 0; } u=105.83って出たんですが、これは何をしているプログラムなんですか

  • 単純挿入法を入れたいんですけど・・・

    #include <iostream> #include <iomanip> #include <cstdlib> //rand関数を使うので using namespace std; void Sort(int *s, int n); //プロトタイプ int main() { const int N = 100; int a[N], i, r, temp; for(i = 0; i < N; i++) a[i] = i; for(i = 0; i < N; i++){ r = rand() % N; temp = a[i]; a[i] = a[r]; a[r] = temp; } cout << "整列前\n----\n"; for(i = 0; i < N; i++) cout << setw(4) << a[i]; cout << '\n'; Sort(a, N); cout << "整列後\n----\n"; for(i = 0; i < N; i++) cout << setw(4) << a[i]; cout << '\n'; return 0; } void Sort(int *s, int n) { //この部分を補って完成させること }

専門家に質問してみよう