如何在单独文件中定义的成员函数中使用成员变量

How to use a member variable in a member function which is defined in a separate file

本文关键字:成员 函数 变量 定义 单独 文件      更新时间:2023-10-16

userInput.hpp

#include <string>
class UserInput{
public:
    std::string rawInput;
    std::string parseUserInput;
}; 

用户输入.cpp

#include <iostream>
#include "userInput.hpp"
#include "stringManipulation.hpp"
using namespace std;
string branchCommand;
string parseUserInput(){
    removeWhiteSpaces(rawInput);
    return branchCommand;
}

我在userInput.hpp中创建了一个带有成员函数parseUserInput的类,我的意思是在userInput.cpp中定义该函数。但是,当我尝试在定义中使用 rawInput 时,我不能不这样做,以便将rawInput声明为 static

是否可以在函数的定义中使用另一个文件中的rawInput字符串,而不会使rawInput变量成为静态变量?

首先,您已经将parseUserInput声明为 hpp 中的字符串字段,而不是函数。 使用参数将其声明为成员函数。

std::string parseUserInput();

其次,在 userInput 中.cpp您定义的是一个名为 parseUserInput() 的全局函数,而不是成员函数。 若要定义 UserInput 类上的成员函数,请使用范围解析运算符::

std::string UserInput::parseUserInput() {
    ...
}

最后,应避免在代码中using namespace std;

您当前的类如下所示:

userInput.hpp

// Missing Header Guards Or #Pragma Once
#include <string>
class UserInput{
public:    
    std::string rawInput;        // Member Variable of UserInput      
    std::string parseUserInput;  // Member Variable of UserInput   
};

用户输入.cpp

#include <iostream>                // Okay    
#include "userInput.hpp"           // Okay
#include "stringManipulation.hpp"  // Okay
using namespace std;   // Bad Practice
string branchCommand;  // non const local Global Variable - can be bad practice 
// Looks like a global function that is not a part of your class
string parseUserInput(){
    removeWhiteSpaces(rawInput);
    return branchCommand;   // returning global variable that isn't used?
}

你的意思是?

userInput.hpp

#ifndef USER_INPUT_HPP
#define USER_INPUT_HPP
#include <string>
class UserInput {
public:
    std::string rawInput; // Member Variable
    std::string parseUserInput(); // Now a Member Function that Returns a std::string
};
#endif // USER_INPUT_HPP

用户输入.cpp

#include <iostream>
#include "userInput.hpp"
#include "stringManipulation.hpp"
std::string branchCommand; // Still a bad idea if not const or static
std::string UserInput::parseUserInput( /* should this take a string from the user? */ ) {
    removeWhiteSpaces( rawInput );
    return branchCommand; // ? ... Still not sure what you are returning.
}

嗨,你有没有想过制作一个 get 函数......

std::string returnRawInput() {return rawInput;}

然后,您可以调用此函数来获取输入...