overloading *, +, -'operators for vector class

前端 未结 4 1378
说谎
说谎 2021-01-06 08:33

I\'m writing a Line class to make numerical methods and I want these operators (*, +, -) to make my code more readable and easier to understand.



        
4条回答
  •  渐次进展
    2021-01-06 09:15

    You should never inherit from std-classes which are not meant for inheritance. Inheriting from classes which do not have a virtual destructor is very dangerous.

    I'd suggest you use aggregation: Make your Line class contain a member of vector type, named myVector_ for example, and implement the desired operators in a way that they use this member variable.

    So you replace all calls to size() to myVector.size() etc:

    Line Line::operator*(double alfa)
    {
        Vector temp;
        int n = myVector_.size();
        temp.resize(n);
        for (int i = 0; i < n; i++)
        {
            temp.at(i) = myVector_.at(i)*alfa;
        }
        return temp;
    }
    

提交回复
热议问题