简体   繁体   English

指向struct成员变量的指针

[英]pointer to member variable of struct

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

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

i want to have a method that will return pointer subName when subName matches with given text. 我想有一个方法,当subName与给定的文本匹配时,该方法将返回指针subName For example something like: 例如:

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

is it possible?? 可能吗?? or is there other way to achieve the desired result? 还是有其他方法可以达到预期的效果?

Yes, it's possible to use test.BranchSub[5].subName . 是的,可以使用test.BranchSub[5].subName

For second part of your question, you should use std::string : 对于问题的第二部分,应使用std::string

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

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

And then 接着

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

is more clear. 更清楚。

You even can use std::vector<BranchSub> instead of BranchSub sub[20] . 您甚至可以使用std::vector<BranchSub>代替BranchSub sub[20]

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

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