2017-06-17 94 views
-5

我无法理解这行从源代码代码在github上:这行代码在C++中意味着什么?

using NodePtr = std::shared_ptr<Node>; 

我读了cppreference页面here,但它没有关于类似的语法的任何信息。尽我所能猜到,它有点像#define,因为从现在开始我使用NodePtr时,它将在内部用std::shared_ptr<Node>代替它。有了这个,我试图测试代码,但它没有奏效。

代码:

test.h

#ifndef TEST_H_ 
#define TEST_H_ 

#include <memory> 
#include <string> 
#include <vector> 
#include <unordered_map> 
#include <utility> 
#include <typeinfo> 
#include <limits> 
#include <functional> 


namespace nnvm { 
class Node; 


using NodePtr = std::shared_ptr<Node>; 


class Node { 
public: 

    ~Node(); 

    inline bool is_variable() const; 
    inline int num_outputs() const; 
    inline int num_inputs() const; 

}; 

} 

#endif // TEST_H_ 

test.cpp

#include "test.h" 
#include <iostream> 


static graphy::NodePtr Create(); 

int main(int argc, char const *argv[]) 
{ 
    /* code */ 

    graphy::Node *node = new graphy::Node(); 
    std::cout << "Hello Graphy!!" << std::endl; 
    return 0; 
} 

以下是错误我得到:

In file included from /usr/include/c++/5/unordered_map:35:0, 
       from test.h:7, 
       from test.cpp:1: 
/usr/include/c++/5/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options. 
#error This file requires compiler and library support \ 
^
In file included from test.cpp:1:0: 
test.h:18:7: error: expected nested-name-specifier before ‘NodePtr’ 
using NodePtr = std::shared_ptr<Node>; 
    ^
test.cpp:5:14: error: ‘NodePtr’ in namespace ‘graphy’ does not name a type 
static graphy::NodePtr Create(); 
      ^
+2

当然有。这是[底部的第三个链接](http://en.cppreference.com/w/cpp/language/type_alias)。 – Rakete1111

+4

这是一个别名。您可以在代码中使用'NodePtr'而不是'std :: shared_ptr '。 – Azeem

+4

请阅读第一条错误消息并按照说明进行操作。 – molbdnilo

回答

2

乍一看哟你的错误是由于命名空间。 using语句位于命名空间nnvm中,而不是Graphy。

'使用'与'typedef'类似。这是允许'nnvm :: NodePtr'表示'std :: shared_ptr'的别名。

更新 作为@UnholySheep所指出的,你还需要增加一个编译器设置,使C++ 11的支持,因为编译器错误状态。

+2

*“#error此文件需要编译器和库支持ISO C++ 2011标准。”* - 这是第一个错误,它与命名空间无关 – UnholySheep

+0

@UnholySheep啊,是的。我停下来注意到第一个错误。但你是对的。这里有更多的错误。 –

0

您看到的错误消息表明您正尝试使用默认为C++ 98模式的旧编译器编译C++ 11代码。你可能需要一个命令行开关,像-std = C++ 11(或类似的东西,取决于你正在使用的编译器)。或者得到一个新的编译器。