overloading *, +, -'operators for vector class

前端 未结 4 1352
说谎
说谎 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:11

    The linker error tells you that your code is missing definitions of two member functions that you declared - the constructor and the destructor:

    Line::Line() {
        // Code of the constructor goes here
    }
    
    Line::~Line() {
        // Code of the destructor goes here
    }
    
    0 讨论(0)
  • 2021-01-06 09:11

    Surely the correct thing is to have a Vector object INSIDE line, and not "inherit" from Vector? Generally inheriting from std:: containers is not a great data... I'm pretty sure a "Line" is not actually a vector, it's a "has a" vector. [The rule for "when you inherit" is "X is a Y", where you make a composite object when "X has a Y" - so there is a Y inside X.]

    You will need to declare your constructor and destructor to get rid of your linking error.

    I would also use const Line& as your input to the math operations, as you neve alter the input.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-06 09:21

    You have to overload the operators at global scope:

    vector<double> operator*(const vector<double>& v, double alfa)
    {
        ...
    }
    
    vector<double> operator+(const vector<double>& v1, const vector<double>& v2)
    {
        ...
    }
    
    vector<double> operator-(const vector<double>& v1, const vector<double>& v2)
    {
        ...
    }
    

    As for the linker errors, it just looks like you didn't implement the Line constructor and destructor.

    0 讨论(0)
提交回复
热议问题