0

I have a simple class, which handle a 3D vector. I have a print method, and a get_coo (which returns with a coordinate of a vector). I want these funkctions to be static methods, so I could use them generally with vectors. But I always got error: a nonstatic member reference must be relative to a specific object

Header:

#include "stdafx.h"
#ifndef my_VECTOR_H
#define my_VECTOR_H

class my_vector{

private:
    double a,b,c; //a vektor három iránya

public:
    my_vector(double a, double b, double c); //konstruktor

    static double get_coo(const my_vector& v, unsigned int k); //koordináták kinyerése, 1-2-3 értékre a-b vagy c koordinátát adja vissza

    void add_vector(const my_vector& v);//összeadás

    static void print_vector(const my_vector& v);
};

#endif

Implementation:

    #include "stdafx.h"
    #include "my_Vector.h"
    #include <iostream>

    my_vector::my_vector(double a = 100, double b= 100, double c= 100):a(a),b(b),c(c){
        //default contstructor
    }

    void my_vector::add_vector(const my_vector& v){
        double     v_a = get_coo(v, 1),
               v_b = get_coo(v, 2),
               v_c = get_coo(v, 3);

        a+=v_a;
        b+=v_b;
        c+=v_c;
    }


    double my_vector::get_coo(const my_vector& v, unsigned int k){
        switch(k){
        case 1:
            return a; //here are the errors
        case 2:
            return b;
        case 3:
            return c;
        }
    }

void my_vector::print_vector(const my_vector& v){
    std::cout << get_coo(v, 1)  << std::endl;
    std::cout << get_coo(v, 2)  << std::endl;
    std::cout << get_coo(v, 3)  << std::endl;
}
3
  • Is this Hungarian? Perhaps you should be using Hungarian notation as well... ;-) Commented Jul 13, 2013 at 19:13
  • Take some time and spell out function names. The effects on build process are negligible and doesn't add any extra code. However, it does make you code more readable to you and others (such as the readers or Stack Oveflow). Commented Jul 13, 2013 at 19:14
  • Why do you want the functions to be static? Commented Jul 13, 2013 at 21:28

1 Answer 1

4

As get_coo is static it doesn't have an object to operate on and you cannot access non-static members without qualifying then with object or pointer to object. Try:

double my_vector::get_coo(const my_vector& v, unsigned int k){
    switch(k){
    case 1:
        return v.a; //here are the errors
    case 2:
        return v.b;
    case 3:
        return v.c;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Should be "cannot access non-static members...".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.