如何调用包含在命名空间中的变量的方法?

How can I call a method of a variable, which contains in a namespace?

提问人:Black Hat 提问时间:6/10/2022 最后编辑:Black Hat 更新时间:6/10/2022 访问量:67

问:

我有这个 C++ 代码:interface.h

    #include <iostream>
    class A{
    public:
        void foo();
    };
    namespace interface{
        ...
        namespace Sounds{
            A val;
        };
    }

我需要调用方法。 我想在以下方面做:.foointerface.cpp

#include "interface.h"

void A::foo(){
    std::cout<<1;
}

interface::Sounds::val.foo();

但克利翁警告我:

No type named 'val' in namespace 'interface::Sounds'

我该怎么办?
编辑:添加了公共

C++ 方法 命名空间

评论


答:

2赞 273K 6/10/2022 #1

您只能在函数体之外声明和定义类型、函数和对象,因此编译器会查找类型而找不到它。您可以调用函数,而不使用仅从函数返回的结果。val

int main() {
  interface::Sounds::val.foo();
}

至少在上面几乎可以成功编译。 被声明为私有,因此除非它被声明为公共,否则无法访问:valvoid A::foo()val.foo()

class A {
 public:
  void foo();
};
2赞 user12002570 6/10/2022 #2

有 2 种方法可以解决这个问题,这两种方法如下所示。

方法 1:先前的 C++17

第一种方法是在头文件中使用 kewyord 进行声明,然后在使用之前在源文件中定义,如下所示:externvalval

接口.h

#pragma once 
#include <iostream>
class A{
    public: //public added here
    void foo();
};
namespace interface{
    
    namespace Sounds{
        //note the extern here . This is a declaration
        extern A val;
    };
}

接口.cpp

#include "interface.h"

void A::foo(){
    std::cout<<1;
}

//definition 
A interface::Sounds::val;

main.cpp


#include <iostream>
#include "interface.h"
int main()
{
    //call member function foo to confirm that it works
    interface::Sounds::val.foo();
    return 0;
}

工作演示

上述修改程序的输出为:

1

方法 2:C++17

您可以使用代替 C++17 及更高版本在标头中定义:inlineexternval

接口.h

#pragma once 
#include <iostream>
class A{
    public: //public added here
    void foo();
};
namespace interface{
    
    namespace Sounds{
        //note the inline used here
        inline A val{};
    };
}

接口.cpp

#include "interface.h"

void A::foo(){
    std::cout<<1;
}

//nothing needed here as we used inline in the header

main.cpp


#include <iostream>
#include "interface.h"
int main()
{
    //call member function foo to confirm that it works
    interface::Sounds::val.foo();
    return 0;
}

工作演示