【问题标题】:Using class instead of struct and constructor issues使用类而不是结构和构造函数问题
【发布时间】:2013-03-25 03:24:06
【问题描述】:

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

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

    当使用neighborAtt 作为结构时,我可以像neighborAttributes currentNode(neighborID, att1, att2); 一样轻松地做到这一点。什么是等效类?

  2. 在.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


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2021-08-31
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多