重载操作符<更改成员变量 [英] overloading operator<< to change member variable
问题描述
我有一个类看起来像这样:
class A {
public:
一个() {};
A&运算符<< (A& a,unsigned int i);
private:
vector< int> abc;
}
我想要提供将对象添加到 abc
使用运算符:
a<< 3,4,5; //应该像几次调用abc.push_back(i)一样
我知道要重载< <
运算符,我还必须重载,
运算符吗?
实际方法如何?
想要保持 a<< 1,2,3
,您可以更改运算符<<
的重载以接受 initializer_list $ c $
#include< initializer_list>
class A {
public:
A(){};
A&运算符<< (std :: initializer_list< int> values);
private:
vector< int> abc;
}
然后实现:
$ b b
A& A :: operator<< (std :: initializer_list< int> values)
{
for(const auto& value:values)
abc.push_back
return * this;
}
只需使用它:
A a;
a<< {1,2,3,4};
你需要确保你有一个C ++ 11兼容的编译器提供这些功能。
I have a class that looks something like this:
class A {
public:
A() {};
A& operator<< (A& a, unsigned int i);
private:
vector<int> abc;
}
I want to offer the ability to add objects to abc
using an operator:
A a();
a << 3,4,5; // should do the same as several calls of abc.push_back(i)
I know that I have to overload the <<
operator, do I also have to overload the ,
operator?
How would the actual method look like?
If you want to keep the aspect of a << 1, 2, 3
you could change your overloading of operator<<
to accept an initializer_list
of int
, instead of a single int
.
#include <initializer_list>
class A {
public:
A() {};
A& operator<< (std::initializer_list<int> values);
private:
vector<int> abc;
}
Then implement it like:
A& A::operator<< (std::initializer_list<int> values)
{
for(const auto& value : values)
abc.push_back(value);
return *this;
}
And simply use it as follows :
A a;
a << {1, 2, 3, 4};
The only thing you need to make sure is you have a C++11 compliant compiler that provides these features.
这篇关于重载操作符<更改成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!