简体   繁体   English

(C++) class 中的获取器和设置器无法按预期工作

[英](C++) Getter and setter in a class not working as intended

I am trying to write a simple code where the getter and setter is used.我正在尝试编写一个使用 getter 和 setter 的简单代码。

Here is the test_class.hpp file这是 test_class.hpp 文件

#ifndef TEST_CLASS_HPP
#define TEST_CLASS_HPP

class test_class
{
private:
    int num;
public:
    test_class(int num);
    ~test_class();
    int& get_num();
    void set_num(int& num);
};


#endif

Here is the test_class.cpp file这是 test_class.cpp 文件

#include<iostream>
#include"test_class.hpp"

test_class::test_class(int num):num(num){};
test_class::~test_class(){};

int& test_class::get_num(){return num;}
void test_class::set_num(int& num){num = num;}

And here is the main function这里是主要的 function

#include<iostream>
#include"test_class.hpp"
#include<random>

int main(){
    test_class obj_test(69);

    int count = 10;
    while (count > 0)
    {
        std::cout << obj_test.get_num() << " at count " << count << std::endl;
        auto new_change = obj_test.get_num() - count;
        obj_test.set_num(new_change);
        count--;
    }
    
}

Aim: As count goes from 10 to 1 in the while loop, the num variable value should also decrease.目标:随着在while循环中count从10变为1,num变量值也应该减少。

Observation: The value of num variable remains constant (initial value of 69) throughout the iteration.观察: num 变量的值在整个迭代过程中保持不变(初始值为 69)。 I played with lvalues and rvalues but I can't make it work as intended.我玩过左值和右值,但我无法让它按预期工作。

void test_class::set_num(int& num){num = num;}

What exactly is happening here?这里到底发生了什么? You assign num to itself.您将num分配给自身。 This code does nothing.这段代码什么都不做。 What you really want is你真正想要的是

void test_class::set_num(int& num){ this->num = num; }

Btw you would avoid this kind of errors if you declared顺便说一句,如果您声明,您将避免此类错误

void test_class::set_num(const int& num)

(or even without & ) which you should do, since you don't modify num inside set_num function. (甚至没有& )你应该这样做,因为你不修改set_num function 中的num

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM