Description
引入了const關鍵詞,用於指定“常”對象及“常”對象成員,提供了對數據的一種保護機制,這C++語言的特色之一。但由此,也引出了一些語法上的要求。這些語法要求,實際上有一套完善的原則,需要熟知。
下面的程序,要利用輸入的兩個數創建一個對象,並調用printxy成員函數輸入兩數之和。下面的程序中,begin到end部分需要改動三處,才能保證程序符合要求並正確輸出。請你找出並修改過來,提交begin到end部分的代碼。
#include <iostream>
using namespace std;
class Test
{
private:
int x;
const int y;
//************* begin *****************
public:
Test(int a, int b);
void printxy(); //(1)
} ;
Test::Test(int a, int b){x=a;y=b;} //(2)
void Test::printxy() //(3)
{
cout<<"x*y="<<x*y<<endl;
}
//************* end *****************
int main()
{
int x1,x2;
cin>>x1>>x2;
const Test t(x1,x2);
t.printxy( );
return 0;
}
Input
Output
Sample Input
3 5
Sample Output
x*y=15
HINT
#include <iostream>
using namespace std;
class Test
{
private:
int x;
const int y;
//************* begin *****************
public:
Test(int a, int b);
void printxy() const; //(1)
} ;
Test::Test(int a, int b):x(a),y(b){} //(2)
void Test::printxy()const //(3)
{
cout<<"x*y="<<x*y<<endl;
}
//************* end *****************
int main()
{
int x1,x2;
cin>>x1>>x2;
const Test t(x1,x2);
t.printxy( );
return 0;
}