【问题标题】:How to make a function inside a class return a vector? [closed]如何使类中的函数返回向量? [关闭]
【发布时间】:2017-11-26 20:11:04
【问题描述】:

我有一个类,我希望其中一个类函数接收一个向量并返回一个不同的向量。我尝试了类似的方法,但在函数声明和定义中出现错误,提示它们不匹配。

错误信息:

example.cpp:11:18: error: prototype for ‘std::vector<int> myClass::myFunction(std::vector<double>&)’ does not match any in class ‘myClass’
 std::vector<int> myClass::myFunction(std::vector<dataType> & myVector){
                  ^
example.cpp:8:22: error: candidate is: std::vector<int> myClass::myFunction(const std::vector<double>&)
     std::vector<int> myFunction(const std::vector<dataType> & );

实际代码:

#include<vector>
#include<iostream>

typedef double dataType;

class myClass{
public:
    std::vector<int> myFunction(const std::vector<dataType> & );
};

std::vector<int> myClass::myFunction(std::vector<dataType> & myVector){
  std::vector<int> results;
  results.resize(myVector.size());
  for(int i=0; i<results.size(); ++i){
    results[i] = 0;
  }

  return results;
}

int main(){
  return 0;
}

【问题讨论】:

  • 添加错误信息。
  • 如果您遇到错误,您应该始终将它们逐字包含在您的问题中。我们不是读心术的人。我们无法猜测您的错误消息。
  • 您缺少const
  • 您的错误信息与代码不匹配。完全没有。
  • 在我将#include &lt;vector&gt; 添加到示例中并编译后...没有错误。

标签: c++ c++11 vector c++14 std


【解决方案1】:

根据错误信息,函数是

SetParallel::checkElements(std::vector<double>&)

原型是

SetParallel::checkElements(const std::vector<double>&)

(在两种情况下都省略了初始const std::vector&lt;int&gt;&amp;

你能看出区别吗?

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多