我正在尝试从使用结构转向使用类,我有几个问题 - 不完全完整,但足以说明我的查询 - 代码(提前感谢您澄清这些):
我在创建接受参数的构造函数时遇到问题,特别是头文件中我当前保留为
neighborAtt(int neighbor_id, int att_1, int att_2);
。当使用
neighborAtt
作为结构体时,我可以很容易地使用neighborAttributes currentNode(neighborID, att1, att2);
。什么是等效类?在 .cpp 文件中,我知道我需要将构造函数定义为
neighborAtt::neighborAtt()
。我是否需要使用这些函数(即包含 neighborAtt::)或者我所做的是否准确?
这是我的头文件:
#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
}
最佳答案
对于第二个构造函数(带参数的构造函数),您的操作与不带参数的构造函数相同。还是我问错了?就像:
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
}
关于c++ - 使用类而不是结构和构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607103/