如何在单独文件中定义的成员函数中使用成员变量
How to use a member variable in a member function which is defined in a separate file
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;}
然后,您可以调用此函数来获取输入...
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法