STL:如何为重载operator=?
有一个简单的例子:
#include <vector>
int main() {
vector<int> veci;
vector<double> vecd;
for(int i = 0;i<10;++i){
veci.push_back(i);
vecd.push_back(i);
}
vecd = veci; // <- THE PROBLEM
}
我需要知道的是如何重载运算符=,以便我可以进行这样的赋值:
vector<double> = vector<int>;
我刚刚尝试了很多方法,但编译器总是返回错误...
有没有什么选择让这段代码在不改变的情况下工作?我可以编写一些额外的行,但无法编辑或删除现有的行。泰。
好的,我明白了。我会用另一种方式问你.. 有没有什么选项可以让这段代码在不改变它的情况下工作?我可以编写一些额外的行,但无法编辑或删除现有的行。泰。
There's simple example:
#include <vector>
int main() {
vector<int> veci;
vector<double> vecd;
for(int i = 0;i<10;++i){
veci.push_back(i);
vecd.push_back(i);
}
vecd = veci; // <- THE PROBLEM
}
The thing I need to know is how to overload operator = so that I could make assignment like this:
vector<double> = vector<int>;
I've just tried a lot of ways, but always compiler has been returning errors...
Is there any option to make this code work without changing it? I can write some additional lines, but can't edit or delete the existing ones. Ty.
OK, I see. I'll ask You in another way..
Is there any option to make this code work without changing it? I can write some additional lines, but can't edit or delete the existing ones. Ty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不以更简单的方式做到这一点:
或者:
两者都是开箱即用的:)
Why not do it in a easier way:
Or:
Both are supported out of the box :)
你不能。赋值运算符必须是成员函数,这意味着它必须是不允许修改的 std::vector 模板的成员(或者 C++ 标准是这么规定的)。因此,请编写一个自由函数:
You can't. The assignment operator must be a member function, which means it must be a member of the std::vector template which you are not allowed to modify (or so the C++ Standard says). So instead, write a free function:
如果这是一个谜题,这会起作用......
If it's a puzzle, this will work...