在函数内部定义class的成员变量

Define member variables of class inside function

我知道有很多关于这个主题的帖子,但我觉得我的情况有点不同。我不知道我想做的事情是否可行,如果不行,请告诉我!现在,我的代码如下所示:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Something
{
   public:
    string location;
    string isLocal;
    string IPAddress;
    string setString(string key)
    {
          //key will be either location, isLocal, or IPAddress  
          //set that value to "found" so when I call the member variable later, it will output found
    }

};

int main(int argc, char* argv[])
{
  DLNA local;
  string answer = local.setString("IPAddress");
  cout << local.IPAddress; // should return "found"
  return 0;
}

基本上,在函数 setString 中,我试图根据传入的字符串将成员变量初始化为默认值。但是,我似乎不知道该怎么做。当我在主函数中调用成员变量时,仅仅声明一个本地 DLNA 并在 setString 函数中设置它的值似乎没有任何影响。有谁知道我该如何解决我的问题,或者这是否可能?

谢谢!

你可能想要这个吧? 在 cout 之后仔细观察那个 endl。这将刷新 "things out"。所以它会在屏幕上打印输出。尝试 运行 没有那个 endl。希望这有帮助

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Something
{
   public:
    string location;
    string isLocal;
    string IPAddress;
    string setString(string key)
    {
        if (key == "location") 
        {
            location = "found";
            return location;
        }
        else if (key == "isLocal") 
        {
            isLocal = "found";
            return isLocal;
        }
        else if (key == "IPAddress") 
        {
            IPAddress = "found";
            return IPAddress;
        }

        return "not found";
    }

};

int main(int argc, char* argv[])
{
  Something local;
  string answer = local.setString("IPAddress");
  cout << local.IPAddress << endl; // should return "found"
  return 0;
}

请参阅 here 以了解有关将变量名称获取为字符串的确切问题的讨论。简而言之 - 不,你不能这样做,尽管有一些方法可以模拟它,但它们会使你的代码难以理解,你应该以不同的方式做事。

在你的情况下,你可以为 setString 成员函数做这样的事情

string setString(string key)
{
    if (key == "location") {
        location = "found";
    } elseif (key == "isLocal") {
    if (key == "isLocal") {
        isLocal = "found";
    } elseif (key == "IPAddress") {
        IPAddress = "found";
    } else {
        // handle unmatched case somehow (error message)
    }
    return "found";
}