繁体   English   中英

指向struct成员变量的指针

[英]pointer to member variable of struct

class Main
{
  Struct BranchSub
  {
    Sub()
    {
      subName[0] = '\0';
    }
    char subName[20];
  };

  struct MainSub
  {
  Sub sub[20];
  };
};

我想有一个方法,当subName与给定的文本匹配时,该方法将返回指针subName 例如:

MainSub test;
if(strcmp(test.BranchSub[5].subName, "Hello") == 0);//return pointer to `test.Branchsub[5].subName`

可能吗?? 还是有其他方法可以达到预期的效果?

是的,可以使用test.BranchSub[5].subName

对于问题的第二部分,应使用std::string

class Main
{
  struct BranchSub
  {
    std::string subName;
  };

  struct MainSub
  {
    BranchSub sub[20];
  };
};

接着

MainSub test;
if(test.sub[5].subName == "Hello")

更清楚。

您甚至可以使用std::vector<BranchSub>代替BranchSub sub[20]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM