[英]function calling within a class C++
在同一个班级里
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函数混淆。
简而言之,直接在此处调用print方法没有问题。 尽管有一些情况需要考虑。
如果您在其他类中具有打印方法,则只需使用myAnotherClass.print(...)
。
如果您需要从基类中显式调用一个打印方法,则可以如底部示例中所示,显式地使用基类作用域,例如MyBaseClass::print(...)
这是一种简单的情况,除非您有全局范围内的打印方法或正在使用的命名空间,否则就无法发生任何冲突。
如果位于全局区域,则可以使用:: print(...)进行调用,如果位于命名空间中,则可以使用myNamespace :: print(...)
尽量不惜一切代价避免使用“ this->”,并将其作为最后的选择。 如果在调用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
关键字,而在静态名称的情况下可以使用类名。
this->print(...);
或Executive::print(...);
您可以完全限定成员函数的调用:
Executive::Executive(std::istream& fin)
{
// ...
if(directive == "print")
{
Executive::print(x);
}
// ...
}
我应该注意,如果要将非静态print
方法添加到另一个不同的类中,则这里不会发生名称冲突的机会。 这是因为要从其包含的类之外实际调用该方法,必须引用某个实例以对其进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.