c++ - 在 C++ 中访问构造函数

标签 c++ oop class constructor

我正在尝试使用类 Node 创建一个 Node 对象:

int main(){
    for(int i=0; i< 20; i++)
        Node *handle = new Node(i, 10);
}

class Node{
 public:
    static vector<Node> map;
    static int totalNodes;
    vector<Node> connections;   
    int NodeID;

    Node(int ID, int weight){
    NodeID = ID;
    CreateConnections(weight);
    totalNodes++;
    map.push_back(*this);
}

出于某种原因我得到了

'Node' : undeclared identifier
'Node' handle : undeclared identifier
 syntax error : identifier node

下课后将 main() 向下移动

unresolved external symbol 
for Node::map and Node::totalNodes

我对 C++ 有点陌生,所以任何提示都将不胜感激。

最佳答案

你必须以;结束你的类定义

 class Node
 {
    //....
    map.push_back(*this);
 };  //^^^Cannot miss ;

同时,您需要将Node 的声明放在main 之前。

还有一点:

 Node(int ID, int weight){
     NodeID = ID;
     CreateConnections(weight);
     totalNodes++;
     map.push_back(*this);
 }//missing closing } on constructor definition

您对 maptotalNodes 有 undefined reference 的原因是: 类的静态成员必须在类外初始化。所以当你内联构造函数试图访问它们时,它们没有被定义。所以你有 undefined reference 。

您应该执行以下操作:

 class Node{
 public:
    static vector<Node> map;
    static int totalNodes;
    vector<Node> connections;   
    int NodeID;
    Node(int ID);
 };


int Node::totalNodes = 0;  //definition of static variables
vector<Node> Node::map;

//^^^define constructor outside class body
Node::Node(int ID){ //your second parameter for ctor not used, so remove it
    NodeID = ID;
    totalNodes++;
    map.push_back(*this);
}

关于c++ - 在 C++ 中访问构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991328/

相关文章:

c++ - 仅在 C++ 源文件中查找字符串的正则表达式

design-patterns - 关于责任链模式,已知的 "gotchas"是什么?

linux - 导致内核崩溃的 Perl 脚本

c++ - 在模板类中定义模板化友元函数

c++ - 使用 v8 的共享库与静态链接的 v8 不兼容?

c++ - 将 Python 3 Unicode 转换为 std::string 的简洁方法

c++ - 类作为参数错误

c++ - 结构和类

html - 垂直排列 div 类图 block

c++ - 为什么我会收到链接器错误?