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

标签 c++

用户输入.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/

相关文章:

c++ - 阶乘在 main 中显示错误答案。在函数中正确计算

c++ - winsock2线程安全吗?

c++ - 为什么我的 C++ 代码比 C 代码慢得多

c++ - [temp.spec]/6 的起源故事?

python - 指定 cython 输出文件

c++ - 每 X 字节删除空字节 c++ WINAPI

c++ - 如何杀死或终止 boost 线程

c++ - 如何将c++库路径添加到xcode

c++ - 以最有效的形式将 32 位值存储为 C 字符串

c++ - OpenGL 缓冲两个初始化