0

我试图实现调用一个类成员来获取同一类的另一个成员函数的默认参数。这是我正在做的事情:

class y {
    virtual vector<int> getLabels();
}

class x: public y {
    virtual vector<int> getLabels();
    listGraph getPlanarGraph(const vector<int> &nodeSe=getLabels());    //want to achieve this. Compiler won't agree 
};

如果没有提供任何内容,称为obj.getPlanarGraph()whereobj是对应类型的,那么我想获取graph. 我知道我可以为此编写一个简单的包装器,如下所示(见结尾),但我更感兴趣的是为什么不允许这样做。对于上面的声明编译错误是:cannot call member function ‘virtual std::vector<int> baseGraph::getLabels() const’ without object.

当我提供this参数时,错误是‘this’ may not be used in this context.

class x: public y {
    virtual vector<int> getLabels();
    listGraph getPlanarGraph(const vector<int> &nodeSe=this->getLabels());    //error here.
};

我想到的解决方法是:

class x: public y {
    virtual vector<int> getLabels();
    listGraph getPlanarGraph(const vector<int> &nodeSet);    //No. 2
    listGraph getPlanarGraph();    //define the function accordingly and call a 'No. 2' from inside.   
};
4

1 回答 1

0
listGraph getPlanarGraph(const vector<int> &nodeSe=this->getLabels());    

... 不可能,因为在调用方法时,this指的是调用该方法的任何类实例,而不是该方法所属的类的实例。this仅指方法执行后该方法所属的类的实例。

至于为什么不可能,上面的行有点类似于调用这样的方法:

x xinstance;
const vector<int> nodeSe labels = this->getLabels();
listGraph lg = xinstance.getPlanarGraph(labels);   

这段代码可以工作,但你可以清楚地看到,它this指的是包含上述代码行的任何类的实例,而不是xinstance. 然而,正如@Ivan Aucamp 在评论中指出的那样,当它在成员函数声明中表示时,this并没有引用任何东西,因为它当时没有定义。

于 2013-07-16T20:59:33.233 回答