define norm as a member function of vector class in c

You are declaring norm() as a friend function, so it is not actually a member of the vector class itself. You are telling the compiler that some external non-member function T norm() is a friend of vector so that it can access vector‘s private members. But then you don’t actually define such a T norm() function!

The correct way to implement norm() as a member, with a definition outside of the class declaration, would look like this instead:

template <typename T>
class vector{
    ...
public:
    ...
    T norm(); // <-- remove 'friend'!
};

template <typename T>
T vector<T>::norm(){ // <-- note the extra <T>!
    T sum{0};
    for (auto i = 0u; i < _size; ++i){
        sum += elem[i];
    }
    return std::sqrt(sum);
}

On a side note:

You might consider using SFINAE to omit the declaration+definition of norm() for T types that std::sqrt() does not support (non-integers/floating-point types, like strings, etc).

Also, your vector class does not implement the Rule of 3/5/0 to manage its inner array properly. You need to add proper copy/move constructors and copy/move assignment operators to it.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top