c++ - 使用类而不是结构和构造函数问题

标签 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::)或者我所做的是否准确?

这是我的头文件:

#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/

相关文章:

c++ - 从 Linux 到 Windows 交叉编译 C++ 应用程序的手册?

c++ - 继承构造函数

php - Yii 和 PHP 初始化与构造问题

c++ - 我真的需要为const对象实现用户提供的构造函数吗?

c++ - 实现智能指针时引用链接相对于引用计数的优势?

c++ - 在 C++ 中在一行的末尾写一个或多个分号会改变什么吗

java - Eclipse无法查看类文件

c# - 在 .net c# 代码中创建类类型

c++ - 指针 vector 和值 vector 之间的差异

c++ - 我应该将 ref 还是拷贝分配给值返回函数?