c++ - 我的班级中的 Setter 函数不能使用 C++
问题描述
所以我是 C++ 的新手,我做了一个简单的程序,在一个类上存储一个变量,但是我做的 setter 函数从来没有用过。我的代码有什么问题,为什么?
主要.cpp:
#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include "ExampleClass.hpp"
void yourMom(std::string test1, std::string test2) {
Test example{};
int Integer1 = std::stoi(test1);
int Integer2 = std::stoi(test2);
example.setA(Integer1);
example.setB(Integer2);
}
int main() {
int a = 5;
int b = 5;
Test example{a, b};
std::string operation{};
char * string;
string = "12 45";
std::string str(string);
int pos = str.find(" ");
std::string a_str = str.substr(0, pos);
std::string b_str = str.substr(pos + 1);
std::cout << example.getA() << " " << example.getB() << "\n";
yourMom(a_str, b_str);
std::cout << example.getA() << " " << example.getB() << "\n";
}
解决方案
首先,这个函数名很好;)
其次,不,你不能在 C++ 中做这样的事情。scope
在 C++ 中有一个叫做 s 的东西。
函数中的in 是Test example{};
在该yourMom
函数的范围内实例化的。这意味着Test example{a, b};
不能被函数Test example{}
内部的 which更改yourMom
。
我该如何解决这个问题?一种选择是通过引用
传递变量。example
该函数看起来像这样,
void yourMom(Test& example, std::string test1, std::string test2) {
int Integer1 = std::stoi(test1);
int Integer2 = std::stoi(test2);
example.setA(Integer1);
example.setB(Integer2);
}
这样,当您将某些内容分配给函数时example
,yourMom
将更改为函数中的example
变量main
。
另一种方法是传入变量的地址。这将是,
void yourMom(Test* example, std::string test1, std::string test2) {
int Integer1 = std::stoi(test1);
int Integer2 = std::stoi(test2);
example->setA(Integer1);
example->setB(Integer2);
}
int main()
{
...
yourMom(&example, a_str, b_str);
...
}
这意味着该函数可以更改函数中的example
变量所具有的地址main
。
实施适合您的!
奖励:还有另一种方法可以做到这一点。它有点先进(取决于您的知识水平)。试着弄清楚,这将是一个有趣的练习:)。提示:它与return
运算符重载有关。
推荐阅读
- c# - c#中比较bool和string
- css - 如何让 Firefox 像 Chrome 和 Safari 一样流畅地渲染 CSS 关键帧动画?
- python - 如何在一行中用“加号和减号”符号编写 Python f 字符串?
- html - 如何使整个按钮可点击?
- c - 如何从我的程序中获取我的堆的当前大小?
- angular - Angular Material Dialog Popup 中出现错误
- assembly - 写入可执行内存时避免自修改代码 (SMC) 机器清除
- html - 如何在没有 CSS 的情况下在 HTML 中制作垂直线?
- sql - 如何在sql中获取行的最小最小值
- javascript - 悬停在导航项上时显示图像