###前提・実現したいこと
classとstructで実装した場合の違いが知りたい。
参照型、値型という違いが起こしている例外処理なきがするが、
structをclassへ変えた時例外処理が発生する理由がわからないので知りたいです。
よろしくお願いいたします。
###発生している問題・エラーメッセージ
tri.a.x = double.Parse(this.textBox1.Text);
例外処理、System.NullReferenceException
###ソースコード
C#
class Point → struct Point へ変更すると正しく動くが、
なぜclassだとだめなのか
namespace triangle3
{
class Point
{
/* x, y 座標を格納する */
public double x;
public double y;
public int int_sum() { int sum = (int)x + (int)y; return sum; } } class triangle { public Point a; public Point b; public Point c; public Point gravity() { /* 3つの座標から重点を求める */ Point gravi = new Point(); gravi.x = (a.x + b.x + c.x) / 3; gravi.y = (a.y + b.y + c.y) / 3; return gravi; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } /* 画面で、3つの座標を入力した後ボタンを押した時 */ public void Click_btn_event( Object sender, EventArgs e) { triangle tri = new triangle(); try { tri.a.x = double.Parse(this.textBox1.Text); tri.a.y = double.Parse(this.textBox2.Text); tri.b.x = double.Parse(this.textBox3.Text); tri.b.y = double.Parse(this.textBox4.Text); tri.c.x = double.Parse(this.textBox5.Text); tri.c.y = double.Parse(this.textBox6.Text); } catch (FormatException) { return; } Point result = new Point(); result = tri.gravity(); MessageBox.Show(string.Format("( {0} , {1} )", result.x.ToString(), result.y.ToString())); } }
}
###補足情報(言語/FW/ツール等のバージョンなど)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/10/16 02:01
2015/10/16 02:21
2015/10/16 02:27