使用类而不是struct和构造函数问题

时间:2013-03-25 03:24:06

标签: c++ class constructor struct

我正在尝试从使用结构转换为使用类,我对我有一些问题 - 不完全完整,但足以说明我的查询 - 代码(提前感谢您澄清这些):

  1. 我在创建一个接受参数的构造函数时遇到问题,特别是头文件中我当前留下neighborAtt(int neighbor_id, int att_1, int att_2);的行。

    使用neighborAtt作为结构时,我可以轻松地将其作为neighborAttributes currentNode(neighborID, att1, att2);。什么是等同类?

  2. 在.cpp文件中,我知道我需要将构造函数定义为neighborAtt::neighborAtt()

    我是否需要使用这些功能(例如包括neighborAtt::)或者我做得准确吗?

  3. 这是我的头文件:

    #if !def connectivity_H
    #define connectivity_H
    
    #include <iostream>
    #include <vector>
    #include <list>
    #include <string>
    #include <sstream>
    #include <fstream>
    
    class listAtt;
    class vecListAtt;
    
    class neighborAtt //contains the neighbour and associated attributes of a node
    {
    public:
        neighborAtt();
        neighborAtt(int neighbor_id, int att_1, int att_2);
    
    
        vecListAtt connFrFile(int file_ext);
        vecListAtt makeList(std::vector<std::list<neighborAtt>> nodeAndInfo, int nodeID, neighborAtt neighAndAtt);  
        neighborAtt getAtt(std::string currentLine);
    
    private:
        int neighborID;
        int attribute1;
        int attribute2;
    };
    
    typedef std::list<neighborAtt> listAtt;
    typedef std::vector<listAtt> vecListAtt;
    
    #endif
    

    和.cpp文件:

    #include "stdafx.h"
    #include "connectivity.h"
    
    neighborAtt::neighborAtt(): neighborID(0), attribute1(0), attribute2(0) {}
    
    //neighborAtt::neighborAtt constructor with arguments 
    
    vecListAtt connFrFile(int file_ext)
    {
        //code
    }
    
    neighborAtt getAtt(std::string line)
    {
        //code
    }
    

1 个答案:

答案 0 :(得分:1)

对于第二个构造函数(带有参数的构造函数),您执行的操作与没有它们的构造函数相同。或者我的问题是错的?它就像是:

neighborAtt::neighborAtt(int neighbor_id, int att_1, int att_2)
 : neighborID(neighbor_id),
   attribute1(att_1),
   attribute2(att_2)
{
}

对于方法,你必须采用相同的方式:

vecListAtt neighborAtt::connFrFile(int file_ext)
{
    //code
}