首页 > 解决方案 > C ++类getter在main中没有返回任何值,但在类中?

问题描述

我希望有人能指出我的方向,为什么我的 getter 函数在声明 setter 的函数之外使用时似乎无法正确访问。

我正在读取一个文件,使用 getline 函数存储每行的变量,然后将消息分配给Message.h中的私有变量。

当我m1.getmessage()readfile()函数中计算 in 时,它的输出非常好,输出正确(我的文本文件中的消息行),但是它只是main(). 我已经尝试了好几个小时了,我一直在阅读有关局部变量的内容,但据我所知,变量已经设置,并且在公共函数中,因此我看不到我要去哪里错了。在我凌晨 4 点拿到酒之前,任何帮助都将不胜感激。

消息.h

#include <iostream>

class Message {
private:
std::string message;
std::string cipher;


public:
    void readFile();

    void setMessage(std::string msg) {
        message = msg;
    }
    void setCipher(std::string ciph) {
        cipher = ciph;
    }

    std::string getMessage() {
        return message;
    }
    std::string getCipher() {
        return cipher;
    }
};

消息.cpp

#include "Message.h"
#include <fstream>
#include <iostream>

void Message::readFile()    {
    std::string fileUsername;
    std::string fileForename;
    std::string fileSurname;
    std::string fileAge;
    std::string fileTime;
    std::string fileHour;
    std::string fileMin;
    std::string fileSec;
    std::string fileCipher;
    std::string fileMessage;
    Message m1;
    std::fstream file;
    std::string filename;
    std::cout << "Please enter file name: " << std::endl;
    getline(std::cin, filename);
    file.open(filename);
    if (file.is_open()) {
        std::cout << "File opened" << std::endl;
    } else {
        std::cout << "Wrong file name" << std::endl;
    }
    while(file.is_open()) {

        getline(file, fileUsername);
        getline(file, fileForename);
        getline(file, fileSurname);
        getline(file, fileAge);
        getline(file, fileHour, ':');
        getline(file, fileMin, ':');
        getline(file, fileSec);
        getline(file, fileCipher);
        getline(file, fileMessage);
        file.close();
    }
    m1.setMessage(fileMessage);
    m1.setCipher(fileCipher);
    m1.getMessage();

};

主文件

#include <iostream>
#include <iomanip>
#include <fstream>
#include "Message.h"
#include "Caesar.h"
#include "XOR.h"


int main() {

    Message m1;
    m1.readFile();
    std::cout << m1.getMessage();


    return 0;
}

main 中的 cout 没有返回任何内容,而如果我将其传输到 m1.readfile() 中,它会完美地输出变量。

这是我第一次尝试面向对象编程,这绝对是我的弱点。提前感谢您的任何建议。

标签: c++variablessettergetterpublic

解决方案


Message::readFile()函数中,您不是在调用函数setMessagesetCipher当前对象,而是在局部变量 m1 上。局部变量在函数结束时被丢弃,消息和密码最终不会被保存。你应该改为打电话

setMessage(fileMessage);
setCipher(fileCipher);
getMessage();

代替

m1.setMessage(fileMessage);
m1.setCipher(fileCipher);
m1.getMessage();

这将更新当前对象的消息和密码变量,然后您可以getMessage()main函数中打印。


推荐阅读