【问题标题】:How to create an object of a nested class?如何创建嵌套类的对象?
【发布时间】:2014-01-10 13:41:51
【问题描述】:

我正在尝试访问我的嵌套类,以便可以在此函数中返回对象:

Graph::Edge Graph::get_adj(int i)
{
    Graph::Edge v;
    int count = 0;
    for(list<Edge>::iterator iterator = adjList[i].begin(); count <= i ;++iterator)
    {
        v.m_vertex = iterator->m_vertex;
        v.m_weight = iterator->m_weight;
    }
    return v;
}

不用担心 for 循环(理论上它应该可以工作)我的主要问题是声明对象 Graph::Edge v; 它不起作用!这是我得到的错误:

$ make -f makefile.txt
g++ -Wall -W -pedantic -g -c Graph.cpp
Graph.cpp: In member function `Graph::Edge Graph::get_adj(int)':
Graph.cpp:124: error: no matching function for call to `Graph::Edge::Edge()'
Graph.cpp:43: note: candidates are: Graph::Edge::Edge(const Graph::Edge&)
Graph.h:27: note:                 Graph::Edge::Edge(std::string, int)
makefile.txt:9: recipe for target `Graph.o' failed
make: *** [Graph.o] Error 1

我想访问

Graph.h:27: note:                 Graph::Edge::Edge(std::string, int)

这是我的类 Graph 的声明方式:(为了简单起见,我取出了函数和一些东西,使其更易于阅读) *

class Graph
{
private:
    vector< list<Edge> > adjList;
public:
    Graph();
    ~Graph();
    class Edge
    {
    public:
        Edge(string vertex, int weight)
        {
            m_vertex = vertex;
            m_weight = weight;
        }
        ~Edge(){}
        string m_vertex;
        int m_weight;
    };

    vector < list < Edge > > get_adjList(){return adjList;}
    //Other functions....

};

基本上,我只需要知道在此函数中声明 Edge 对象的正确方法。我真的很困惑,不知道除了 Graph::Edge v 还能做什么;

【问题讨论】:

  • 我不明白get_adj(i)的意思,它应该返回顶点i的整个邻接表还是一些邻接表的i-th邻接项未指定 顶点?我假设您的 adjList 实际上是每个顶点的邻接列表,这意味着 adjList[i] 包含顶点 i 的邻接。

标签: c++ oop object return


【解决方案1】:

您可以看到innerouter 类中,因此可以创建inner 对象或实例,并且可以像下面的sn-p 那样调用方法。

#include<iostream>
using namespace std;
class outer
{
    int x;
    public:
        class inner
        {
            public:
                void f(){
                    outer obj;
                    obj.x=10;
                    obj.display();
                }
        };
        void display()
        {
            cout<<x;
        }

};
int main(){
    outer::inner p;
    p.f();
    return 0;
}
//output=10

【讨论】:

    【解决方案2】:

    您的问题是您在 Edge 类 (Edge(string vertex, int weight)) 中声明了一个构造函数,因此您没有默认构造函数。当您尝试创建 Edge 类的实例时(您使用 Graph::Edge v 执行此操作),它会尝试调用此默认构造函数。

    您需要显式声明Edge() 默认构造函数,或者使用您创建的构造函数声明变量。

    【讨论】:

      【解决方案3】:

      Graph::Edge 没有默认构造函数(不带参数的构造函数) - 它只有一个带 stringint 的构造函数。您要么需要像这样提供默认构造函数:

      Edge()
      {
        // ...
      }
      

      或者在构造对象时传递一个string和一个int

      Graph::Edge v("foo", 1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-05
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多