C ++类getter在main中没有返回任何值,但在类中是什么?

问题描述 投票:1回答:4

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

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

当我在m1.getmessage()函数中输入readfile()时,它输出绝对正确,输出正确(来自我的文本文件的消息行),但它只是在main()中给出空白输出。我一直试图让我的头围绕它好几个小时,我一直在阅读局部变量,但据我所知,变量已经设置,并且在公共函数中,因此我看不到哪里出错了凌晨4点到达vino之前,我会非常感激您的帮助。

Message.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;
    }
};

Message.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();

};

Main.cpp的

#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;
}

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

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

c++ variables setter getter public
4个回答
2
投票

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

getMessage()

代替

main

这将更新当前对象的消息和密码变量,然后您可以从Message m1;函数打印readFile()


0
投票

在readfile中创建一个局部变量m1。然后它会在函数结束时被丢弃。您可能要么返回对象,要么设置当前实例


0
投票

您不必在该类的成员函数中创建对象

我的建议:

  • setMessage(fileMessage);中省略/删除setCipher(fileCipher);
  • 直接调用函数 qazxsw poi qazxsw poi qazxsw poi

0
投票

你可以用这个;指向您当前正在处理的对象的指针。如下。

getMessage();

要么

this->setMessage(fileMessage);
© www.soinside.com 2019 - 2024. All rights reserved.