首页 > 解决方案 > 关于重新声明友元函数的警告

问题描述

我有啊,我有

#ifndef _FOO_
#define _FOO_
namespace FOO {
    const std::string& getName();
}
#endif

在 Bh 我有

#ifndef _BAR_
#define _BAR_
namespace FOO {
    //forward declaration
    const std::string& getName();
}

namespace BAR {
class Baz {
private:
   static std::string& get();
public:
   friend const std::string& FOO::getName();
}
}
#endif

在 B.cpp

#include "B.h"
namespace BAR {
       std::string& Baz::get() {
            static std::string s;
            return s;
       }
}

在 A.cpp 中:

#include "A.h"
#include "B.h"
namespace FOO {
const std::string& getName() {
    return BAR::Baz::get();
}
}

当我编译时,我收到来自 GCC 的以下警告:

'const string& FOO::getName()' 在同一范围内的冗余重新声明。[-Wredundant-decls]

在 A.cpp 编译期间,警告是针对 Ah 的。怎么来的?

标签: c++

解决方案


在 A.cpp 编译期间,警告是针对 Ah 的。怎么来的?

警告消息解释了其存在的原因。你不必要地声明FOO::getName了两次。第二个声明称为重新声明。

解决方案:与其手动重新声明其他头的内容,#include 不如将 Ah 放入 Bh 的包含守卫中,将防止多余的重新声明。


PS 您使用的标头保护宏保留给语言实现。因此,程序的行为将是未定义的。


推荐阅读