在类的CPP文件中求解名称扣

Solving name-clash in cpp file of a class

本文关键字:CPP 文件      更新时间:2023-10-16

我想在foo的" bar"方法中从" somelib"中调用未指示的函数" bar"。

// .h
class Foo
{
    int bar();
};
// .cpp
#include "Foo.h"
#include <somelib> // contains unscooped function bar()
int Foo::bar()
{
    return bar(); // unwanted recursive function
}

解决方法的一种方法是使用辅助功能,例如" bar_helper"

// .cpp
#include "Foo.h"
#include <somelib> // contains unscooped function bar()
// unnamed namespace
namespace
{
    int bar_helper()
    {
        return bar(a);
    }
}
int Foo::bar()
{
    return bar_helper();
}

  • 可以变得更漂亮吗?
  • 有更好的解决方案吗?

如果非会员bar函数在全局范围中,则可以使用范围操作员::

int Foo::bar()
{
    return ::bar();
}

在范围上明确说明全局一个:

return ::bar();
       ^^