我想學習C++。我希望改變公衆成員數據2的值。在第二個cout聲明中,爲什麼我沒有獲得10.5值?如何更改C++中公用數據字段的值?
class Test
{
private:
int data1;
public:
float data2;
void function1()
{
data1=2;
}
float function2()
{
data2=3.5;
return data2;
}
};
int main()
{
Test obj2;
Test obj1;
cout<<"value of public member data2 is "<< obj2.function2()<<endl;
obj2.data2=10.5;
cout<<"new value of data2 is " <<obj2.data2<<where as its previous value
was obj2.function2()<<endl;
}
你總是設置'data2'在'函數2()'你回來之前,能有什麼辦法? – user0042
您正在第二個cout語句中調用function2。該函數將data2值更改爲3.5,並返回該值,然後由cout打印。 – JPX
對不起,我修改了Cout語句。它應該給「數據2的新值是10.5,而之前的值是3.5」,但在這兩個地方 – rida