将vector作为对象从一个类传递到另一个类
passing vector from one class to other as object
我有两个类Net
和GA
,我想通过main
将一个向量从GA
传递到Net
。考虑下面的代码:
class GA {
inline vector <double> get_chromosome(int i) {
return population[i];
}
}
class Net {
int counter;
Net::setWeights(vector <double> &wts){
inpHidd = wts[counter];
}
}
main(){
net.setWeights( g.get_chromosome(chromo) );
}
错误是:
Network.h:43:8: note: void Network::setWeights(std::vector<double>&)
void setWeights ( vector <double> &wts );
^
Network.h:43:8: note: no known conversion for argument 1 from ‘std::vector<double>’ to ‘std::vector<double>&’
任何想法?
这很简单:根据标准,只有const引用可以绑定到临时对象。
g.get_chromosome(chromo)
返回一个临时对象,Net::setWeights(vector <double> &wts)
尝试用常规引用绑定到它。
如果你不打算改变向量,Network::setWeights(std::vector<double>& wts)
应该是Network::setWeights(const std::vector<double>& wts)
,或者Network::setWeights(std::vector<double> wts)
如果你做。
最后一个选项是移动向量,在这种情况下,您应该使用移动语义。
如果不知道如何声明population,我会说change return population[I];对于返回种群;在get_chromosome
我创立了答案。实际上,问题是与网络接收端的参考有关。你不需要这个;如果你不改变向量。@ david是对的。
考虑下面的例子:
#include <iostream>
using namespace std;
void addone (int &x){
x = x + 10;
}
void addtwo(int x){
x = x + 10;
}
int main (){
int x = 10;
addone(x);
cout<<x;
int y = 10;
addtwo(y);
cout<<endl<<y;
}
输出为:
20
10
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口