类C++中的函数调用

function calling within a class C++

本文关键字:函数调用 C++      更新时间:2023-10-16

在同一个类中,我有

Executive::Executive(std::istream& fin){
std::ifstream dFin(argv[2]);
if(!dFin.is_open()){
    std::cout <<"Could not open directives file.";
    std::cout <<endl;
}
else{
    std::string directive;
    dFin >>directive;
    int x;
    dFin >>x;

    if(directive=="print"){
    }

和功能

void Executive::print(int i) const{
if(i>MAX_NUM_POLYNOMIALS){
    std::cout <<"Sorry, " <<i <<" is not within the known polynomials.";
    std::cout <<endl;
}
else{       
    pNom[i].print(std::cout);
    std::cout << i <<'n';
}

}

在第一个代码的最后一段,如何从第二个代码调用打印函数?它们在同一个类中,我不想将调用它与在第二部分中从另一个类调用的打印函数混淆。

简而言之,在这里直接调用 print 方法没有问题。下面有一些方案可供考虑。

如果您在其他类中具有打印方法,则只需使用 myAnotherClass.print(...)

如果需要从基类显式调用打印方法,则可以显式使用基类范围,如底部的示例所示,例如MyBaseClass::print(...)

这是一种简单的情况,除非在全局范围内具有打印方法或使用命名空间,否则不能发生任何冲突。

如果它在全局区域中,则可以使用 ::p rint(...)

调用它,如果它在命名空间中,则可以使用 myNamespace::p rint(...)

尽量不惜一切代价避免"这个>",并将其作为最后的手段。如果您在调用 print 的方法中有"print"参数,那么如果您由于某种原因无法更改参数名称,这可能是一种情况。

最后,在

理论课之后,这里是实际示例:

Executive::Executive(std::istream& fin){
std::ifstream dFin(argv[2]);
if(!dFin.is_open()){
    std::cout <<"Could not open directives file.";
    std::cout <<endl;
}
else{
    std::string directive;
    dFin >>directive;
    int x;
    dFin >>x;

    if(directive=="print") {
        print(x);                // calling the method of the current class
        MyBaseClass::print(x);     // calling the method of the base class
        myAnotherClass.print(x); // classing the method of a different class
        ::print(x);              // calling print in the global scope
        myNamespace::print(x);   // calling the method in a dedicated namespace
    }
如果你想

绝对确定你正在调用自己的函数,你可以使用this关键字(如果它不是静态函数)或类名(如果它是静态的)。

this->print(...);Executive::print(...);

您可以完全限定成员函数以调用:

Executive::Executive(std::istream& fin)
{
  // ...
  if(directive == "print")
  {
    Executive::print(x);
  }
  // ...
}

我应该注意,如果您要将非静态print方法添加到另一个不同的类中,则此处不会发生名称冲突。这是因为要从其包含类外部实际调用该方法,您必须引用某个实例来调用它。