C++ 类私有成员的功能不会改变 使用名称空间std; 类图 { 私人: 浮动结果=0; 公众: void func_1(); 无效设置(浮动计数器); float getres(); }; 无效映射::setres(浮点计数器) { 结果=计数器; } 浮点映射::getres() { 返回结果; } 无效映射::func_1() { float num_0=0,num_1=0,sum=0,i; 地图运行; cout

C++ 类私有成员的功能不会改变 使用名称空间std; 类图 { 私人: 浮动结果=0; 公众: void func_1(); 无效设置(浮动计数器); float getres(); }; 无效映射::setres(浮点计数器) { 结果=计数器; } 浮点映射::getres() { 返回结果; } 无效映射::func_1() { float num_0=0,num_1=0,sum=0,i; 地图运行; cout,c++,class,scope,member-access,C++,Class,Scope,Member Access,在函数中,您正在创建映射类型的局部变量 using namespace std; class map { private: float result= 0; public: void func_1(); void setres(float counter); float getres(); }; void map::setres(float counter) { result= counter; } fl

在函数中,您正在创建映射类型的局部变量


using namespace std;

class map
{
    private:
        float result= 0;
    public:
        void func_1();
        void setres(float counter);
        float getres();
};
void map::setres(float counter)
{
    result= counter;
}
float map::getres()
{
    return result;
}
void map::func_1()
{
    float num_0=0, num_1=0, sum=0, i;
    
    map run;
    
    cout << run.getres() << " Result." << endl;
    if(result != 0)
        cout << "We already have a result saved and it's: " << run.getres() << endl;
    else
    {
        cout << "Give me first number: ", cin >> num_0;
        cout << "Give me second number: ", cin >> num_1;
        sum= num_0+num_1;
        cout << "Result is: " << sum << endl;
    }
    cout << "The program will save the result." << endl;
    run.setres(sum);
    cout << "The saved result is: " << run.getres() << "\nPress 1 to repeat the function and check\nif the result is saved." << endl;
    cin >> i;
    if(i==1)
        run.func_1();    
}

int main()
{
    map go;
    go.func_1();
    return 0;
}

已更改的数据成员结果。也就是说,函数不会更改为其调用函数的对象的数据成员结果

此外,例如在这个代码片段中

map run;
您正在访问为其调用成员函数的对象(在main中声明的对象
go
)的数据成员结果

因此,请删除函数中的声明

if(result != 0)

不要使用诸如
run.getres()
之类的表达式,而只使用
getres()
this->getres()
,问题在于函数没有使用调用该方法的对象的成员。相反,您在函数内部创建了一个新实例:

map run;
->


cout将值保存到
run
,并调用
run.func_1()
进行检查,但随后在那里调用
run.getres()
。此
run
是新的
map
对象,与保存数据的
run
不同

您选中了
result!=0
,但使用了
run.getres()
打印结果。此处不一致

而不是

cout << this->getres() << " Result." << endl;
cout
map run;
void map::func_1()
{
    float num_0=0, num_1=0, sum=0, i;
    
    map run;  // <---------- here
    //...
cout << run.getres() << " Result." << endl;
cout << getres() << " Result." << endl;
cout << this->getres() << " Result." << endl;
    cout << run.getres() << " Result." << endl;
    if(result != 0)
        cout << "We already have a result saved and it's: " << run.getres() << endl;
    cout << result << " Result." << endl;
    if(result != 0)
        cout << "We already have a result saved and it's: " << result << endl;
    cout << getres() << " Result." << endl;
    if(getres() != 0)
        cout << "We already have a result saved and it's: " << getres() << endl;