Last active
March 29, 2018 12:55
-
-
Save coligne/a235eaf5f535df8f791c8f794d17635e to your computer and use it in GitHub Desktop.
コピーコンストラクタと代入演算子の意義
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//main関数が終了するのとともにメモリの二重解放エラーが生じる | |
#include<iostream> | |
class Numeric{ | |
private: | |
int length; | |
int *num; | |
public: | |
//コンストラクタ,メンバ変数numを長さlength=Numのint型の動的配列としてメモリを確保し,すべてを0で初期化 | |
Numeric(int Num){ | |
length = Num; | |
num = new int[length]; | |
for(int i = 0;i<length;i++){ | |
num[i] = 0; | |
} | |
}; | |
//デストラクタ | |
~Numeric(){ | |
delete [] num; | |
}; | |
//メンバ変数(int型配列)numのすべてに引数Nを代入 | |
void Set(int N){ | |
for(int i = 0;i<length;i++){ | |
num[i] = N; | |
} | |
}; | |
//メンバ変数numの0番目の添字の値を出力 | |
void Print(){ | |
std::cout << "num[0] = " << num[0] << std::endl; | |
}; | |
//別のオブジェクトの0番目の要素との比較 | |
void Compare(Numeric n){ | |
if(num[0] == (n.num)[0]){ | |
std::cout << "おんなじ大きさ" << std::endl; | |
}else{ | |
std::cout << "ちがう大きさ" << std::endl; | |
} | |
}; | |
}; | |
int main(int argc, char **argv){ | |
Numeric n1(100), n2(50); //インスタンス化 | |
n1.Set(100); //オブジェクトn1のメンバ変数である配列numのすべての値を100にする. | |
n2.Set(50); //オブジェクトn1のメンバ変数である配列numのすべての値を50にする. | |
n1.Print(); | |
n2.Print(); | |
n1.Compare(n2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment