首页 > 解决方案 > 我的班级中的 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++c++17

解决方案


首先,这个函数名很好;)
其次,不,你不能在 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);
}

这样,当您将某些内容分配给函数时exampleyourMom将更改为函数中的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运算符重载有关。


推荐阅读