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



我在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();

但是cleon警告我:

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

我该怎么办?
编辑:public被添加

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

方法1:先验c++ 17

第一种方法是在头文件中使用extern关键字来声明val,然后在使用它之前在源文件中定义val,如下所示:

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;

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

方法二:c++ 17

您可以使用inline代替extern在c++ 17和以后的头中定义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

main.cpp


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

演示工作

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

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

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

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

最新更新