【问题标题】:How can I call a method of a variable, which contains in a namespace?如何调用包含在命名空间中的变量的方法?
【发布时间】:2022-06-10 21:00:37
【问题描述】:

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

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

我需要调用.foo 方法。 我想在interface.cpp做:

#include "interface.h"

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

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

但克莱恩警告我:

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

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

【问题讨论】:

    标签: c++ methods namespaces


    【解决方案1】:

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

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

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

    class A {
     public:
      void foo();
    };
    

    【讨论】:

      【解决方案2】:

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

      方法一:C++17 之前

      第一种方法是在val声明的头文件中使用externkewyord,然后在使用之前在源文件中defineval如下图:

      interface.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;
          };
      }
      

      interface.cpp

      #include "interface.h"
      
      void A::foo(){
          std::cout<<1;
      }
      
      //definition 
      A interface::Sounds::val;
      

      ma​​in.cpp

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

      Working demo

      上述修改程序的输出为:

      1
      

      方法二:C++17

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

      interface.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{};
          };
      }
      

      interface.cpp

      #include "interface.h"
      
      void A::foo(){
          std::cout<<1;
      }
      
      //nothing needed here as we used inline in the header
      

      ma​​in.cpp

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

      Working demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-09
        • 2013-01-08
        • 2011-07-14
        • 1970-01-01
        • 1970-01-01
        • 2016-07-07
        • 2017-01-13
        • 1970-01-01
        相关资源
        最近更新 更多