【发布时间】:2013-03-25 03:24:06
【问题描述】:
我正在尝试从使用结构转向使用类,我有几个问题 - 不完全完整,但足以说明我的查询 - 代码(提前感谢您澄清这些):
-
我在创建一个接受参数的构造函数时遇到问题,特别是我目前保留为
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类的每个函数都需要在 .cpp 文件(即neighborAtt::getAtt(....))中进行范围限定。这也适用于您的构造函数(所有构造函数)。您的 ctr 采用三个整数时遇到了什么“问题”? -
当您说从结构到类时,您是指从字面上将“结构”更改为“类”,还是您在谈论一些更高级别的概念?结构和类在 C++ 中是一回事。唯一的区别是结构中的东西默认是公共的,而类中的东西默认是私有的。也许你的意思是你想使用结构和 C 不提供的东西,比如成员函数。
标签: c++ class constructor struct