【问题标题】:cant access vector object's function through -> operator无法通过 -> 运算符访问向量对象的函数
【发布时间】:2017-06-02 23:32:18
【问题描述】:

这是一个向量的基本二分搜索函数。我想访问一个对象的 get 函数,但我得到了错误。

bool binFindInVec(vector<Client> *vec,string sur){


    int from,to,pos;

    from = 0;
    to = vec->size()-1;


    while(from<=to){

        pos = (from+to)/2;
        if(vec[pos]->getSurname() == sur){
            return true;
        }
        else if(vec[pos]->getSurname() > sur){
            to = pos-1;
        }
        else{
            from = pos + 1;
        }
    }
    return NULL;    
}

错误:

在函数'bool binFindInVec(std::vector*, std::string)'中:
176 14 [错误] '->' 的基本操作数具有非指针类型 'std::vector'
179 19 [错误] '->' 的基本操作数具有非指针类型'std::vector'

【问题讨论】:

  • 你可能想要(*vec)[pos].getSurname()
  • 另外,您可以通过传递引用来简化事情:bool binFindInVec(vector&lt;Client&gt;&amp; vec, string sur){。然后你可以使用:vec[pos].getSurname().
  • 您可能还想考虑一下为什么需要将指针传递给向量而不是引用。
  • 由于vecvector&lt;Client&gt; *vec[x](又名*(vec + x))是vector&lt;Client&gt;

标签: c++ pointers vector operator-keyword


【解决方案1】:

编写vec[pos]-&gt;getSurname() 假定vec 的元素是指针(或智能指针)。由于您将纯Client 对象的向量作为指针传递,因此您需要取消引用vec 才能使用operator[]

【讨论】:

  • 不知道为什么这被否决了。这看起来是正确的。不确定你的意思是什么
  • 我的意思是你需要写这个(*vec)才能使用operator[]
  • 您可能希望将其编辑到答案中然后进行改进。
【解决方案2】:

你应该在调用它的 operator[] 之前取消对 'vec' 的引用:

(*vec)[pos].getSurname();

更好(也更安全),通过引用传递向量参数。不作为指针:

bool binFindInVec(vector<Client> const& vec,string sur)

【讨论】:

  • 如果您实际上并未操作矢量,也请通过 const&amp;
  • 感谢我使用了 const& 因为我实际上并没有操纵向量
猜你喜欢
  • 1970-01-01
  • 2016-06-30
  • 2013-06-10
  • 2015-12-28
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多