用户输入.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;
在您的代码中。
关于c++ - 如何在单独文件中定义的成员函数中使用成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43904368/