应如何使用静态/非静态函数
How should static/non static functions be used?
我有一个简单的类,它处理一个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;
}
}
相关文章:
- enable_if转换构造函数(静态强制转换,is_base_of)
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 检查编译时是否存在静态函数
- 名称隐藏对静态函数继承的实例使用
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 类中静态函数C++意外结果
- 在工人类中使用不同类的静态函数进行实验
- 类 Referention 中C++回调函数引用非静态函数
- 指向模板上下文中的成员函数或静态函数的指针
- 如何检测 Clang AST C++中的静态函数
- 内联asm编译器屏障(内存阻塞器)是算作外部函数,还是算作静态函数调用
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 如何在静态函数中使用成员函数数组
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- C++无法访问或使用静态函数
- 如何将 cpp 文件中的静态函数公开给其他文件
- 将函数的引用设置为其他 c++ 文件中的非静态函数
- 方法的静态函数的等价性
- C++ - 模板类 -> 静态函数 -> 静态函数指针的链接错误