2012C++程序設計實驗報告【6.1】

/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:this指針問題

* 作 者: 王琳
* 完成日期: 2012年 3 月26日
* 版 本 號:6-1

* 對任務及求解方法的描述部分
* 輸入描述:下面的程序存在編譯錯誤。有兩種方法可以修改,請給出這兩種修改方案
* 問題描述:

* 程序輸出: ......
* 程序頭部的註釋結束
*/

源程序:

錯誤源程序:

 

class C
{
private:
	int x;
 public:
	C(int x){this->x = x;}
	int getX(){return x;}
};
void main()
{
	const C c(5);
	cout<<c.getX();
	system("pause");
}

修改後的源程序(第一種修改方案):

#include <iostream>
using namespace std;
class C
{
private:
	int x;
 public:
	 C(int x){this->x=x;}
	int getX()const{return x;}//getX後加const
};
void main()
{
	const C c(5);
	cout<<c.getX();
	system("pause");
}

修改後的源程序(第二種修改方案):

#include <iostream>
using namespace std;
class C
{
private:
	int x;
 public:
	 C(int x){this->x=x;}
	int getX(){return x;}
};
void main()
{
	 C c(5);//將C前面的const去掉
	cout<<c.getX();
	system("pause");
}
運行結果:


感想:

public裏的字符類型要與main函數裏的數據類型相同!平時要注意細節問題,而且,學會運用不同的方法解決同一類問題,當然,基礎就是課本上的基礎知識能夠熟練掌握,可是我貌似還差得有點遠,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章