C ++使用命名空间避免长路径 [英] C++ using namespaces to avoid long paths

查看:140
本文介绍了C ++使用命名空间避免长路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还在学习C ++,我从来没有真正创建自己的命名空间。我正在试验他们,当我得到大多数事情工作,有一件事,我仍然似乎不能做。我想能够在类中调用一个静态方法,而不需要输入像 NameOfClass :: method 。这是我认为代码应该看起来像,但它无法编译:

I am still learning C++, and I have never really created my own namespaces before. I was experimenting with them and while I got most things to work, there's one thing that I still can't seem to do. I would like to be able to call a static method within a class without typing something like NameOfClass::method. Here is what I thought the code should look like, but it fails to compile:

文件 Ah p>

File A.h,

namespace Test
{
    class A
    {
        public:
            static int foo() { return 42; }
    };
}

档案 main.cpp

#include <iostream>

#include "A.h"

using namespace std;
using namespace Test::A;

int main()
{
    cout << foo() << endl;

    return 0;
}

编译器给我:

main.cpp:6: error: ‘A’ is not a namespace-name
main.cpp:6: error: expected namespace-name before ‘;’ token
main.cpp: In function ‘int main()’:
main.cpp:10: error: ‘foo’ was not declared in this scope

是否可以在不输入 A :: foo / p>

Is it possible to do what I am trying to do without typing A::foo?

推荐答案

没有办法,你需要为静态方法指定类名。

There is no way around it you need to specify the class name for static methods.

using namespace Test;

然后:

int answerToEverything = A::foo();

这篇关于C ++使用命名空间避免长路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆