c++编译器找不到重载命名空间的函数

问题描述 投票:0回答:1

我有以下四个文件,

//struct.h
#pragma once
namespace coffee {
    class MD2 {};
    class Recorder{};
    class Book{};
}


//setup.h
#pragma once
#include "struct.h"
void wire(coffee::MD2 md2, coffee::Book book){}

//strategy.h
#pragma once
#include "struct.h"
#include "setup.h"
namespace strategy {
    int wire(coffee::MD2 md2, coffee::Recorder recorder) {}
    int setup(coffee::MD2 md2, coffee::Recorder recorder, coffee::Book book) {
        wire(md2, recorder);
        wire(md2, book); // <--- cant find this function
    }
}

//main.cpp
#include <iostream>
#include "strategy.h"
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

头文件中没有

using namespace X
,但是编译器还是找不到
wire(md2, book)
,请问这是为什么?

c++ namespaces
1个回答
0
投票

如评论中所述,命名空间

wire
中的
strategy
遮蔽了 struct.h 中包含的
wire
。通过在前面添加
::
来访问该函数。

例如,以下打印

foo
而不是
bar::foo

#include <iostream>

void foo() {
    std::cout << "foo" << std::endl;
}

namespace bar {
    void foo() {
        std::cout << "bar::foo" << std::endl;
    }

    void baz() { ::foo(); }
}

int main() {
    bar::baz();
}
© www.soinside.com 2019 - 2024. All rights reserved.