通过set / get方法修改类

编程入门 行业动态 更新时间:2024-10-10 14:25:01
本文介绍了通过set / get方法修改类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图通过get / set方法修改类中的对象。我不明白如何仅使用get / set方法来更改值。

trying to modify object in the class via get/set methods. I can't understand how change value just only use get/set method.

预期输出:输出:89。

expected output : "Output : 89".

实际输出:输出:0

#include<iostream> using namespace std; class TestClass{ public: int getValue() const{ return _value; } void setValue(int value) { _value = value; } private: int _value; }; class A{ public: TestClass getTestClass() const{ return _testClass; } void setTestClass(TestClass testClass) { _testClass = testClass; } private: TestClass _testClass; }; int main() { A a; a.getTestClass().setValue(89); cout<<"Output :"<<a.getTestClass().getValue(); }

推荐答案

替换

TestClass getTestClass() const{ return _testClass; }

with

TestClass& getTestClass() { return _testClass; }

您要返回参考,否则,您只是返回该变量的副本。但是请记住,返回(非const)对类的成员变量的引用不是一种好的设计方法。

You want to return a reference otherwise you are just returning a copy of the variable. But Keep in mind that returning a (non-const) reference to the member variables of a class is not a good design approach.

某些事情:

  • 请不要使用使用命名空间标准; -阅读这里为什么。

请不要命名变量 _testClass - m_testClass 代替。您可以阅读听到有关推理。

please don't name your variables _testClass - go with m_testClass instead. You can read hear about the reasoning.

更多推荐

通过set / get方法修改类

本文发布于:2023-11-25 21:21:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!