类C++中的函数调用
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 方法没有问题。下面有一些方案可供考虑。
如果您在其他类中具有打印方法,则只需使用 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
方法添加到另一个不同的类中,则此处不会发生名称冲突。这是因为要从其包含类外部实际调用该方法,您必须引用某个实例来调用它。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销