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.
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
}
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.
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;
}
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.