且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重载操作符<更改成员变量

更新时间:2023-11-11 20:07:28

想要保持 a<< 1,2,3 ,您可以更改运算符<< 的重载以接受 initializer_list $ c $



pre> #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.