应如何使用静态/非静态函数

How should static/non static functions be used?

本文关键字:静态函数 静态 何使用      更新时间:2023-10-16

我有一个简单的类,它处理一个3D向量。我有一个print方法和一个get_coo(返回向量的坐标)。我希望这些函数是静态方法,所以我可以将它们与向量一起使用。但我总是犯错误:非静态成员引用必须相对于特定对象

标题:

#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

实施:

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

由于get_coo是静态的,因此它没有可操作的对象,并且在没有对象或指向对象的指针的情况下,您无法访问非静态成员。尝试:

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