如何从静态成员函数中调用非静态成员函数?
问题描述:
我需要从同一类的非静态成员函数,如调用非静态成员函数:如何从静态成员函数中调用非静态成员函数?
class bintree {
private:
float root;
bintree *left;
bintree *right;
public:
bintree() : left(nullptr), right(nullptr) {
}
bintree(const float &t) : root(t), left(nullptr), right(nullptr) {
}
~bintree() {
if (left != nullptr)
delete left;
if (right != nullptr)
delete right;
}
static void niveles(bintree *);
static bintree *dameBST(float** array, int depth, int left = 0, int right = -1);
void quickSort2D(float** arr, int left, int right, int n);
};
我的问题是在dameBST功能时,我称之为quickSort2D程序美眉用“分段故障: 11'消息。
bintree *
bintree::dameBST(float **array, int depth, int left, int right)
{
int n=0;
depth++;
bintree *t = new bintree;
bintree *tl;
bintree *tr;
if(depth%2 != 0) { n = 1; }
quickSort2D(array, left, right -1, n);
if (right == -1) {right = 10;}
if (left == right) { return nullptr; }
if(left == right - 1) { return new bintree(array[left][n]); }
int med = (left + right)/2;
t->root = array[med][n];
tl = dameBST(array, depth, left, med);
tr = dameBST(array, depth, med + 1, right);
t->left = tl;
t->right = tr;
return t;
我不明白为什么。
答
非静态成员函数是必须在类的实例上调用的方法。在静态上下文中没有实例。只有班。
如果你有类的对象t
binkree
可以调用方法quickSort2D
:
t.quickSort2D(...)
UPDATE 您还可以从非静态函数静态方法而不是相反
+0
其实它是t-> quickSort2D()因为成员引用类型'bintree *'是一个指针,但改变后它也不起作用,我有'分段错误:11' –
+0
@SakinaLaanani当然,我应该改变为它的名字......无论如何,看起来他没有'吨打算调用这种方法称为't'。这就是为什么有一个错误 –
不要: ),如果你需要这样做,那意味着静态函数首先需要成为一个成员函数。 – alfC
嗯,我猜传统的答案是将实例作为参数传递,然后从静态函数内部调用实例方法。 –