【问题标题】:request for a member of non-aggregate type?请求非聚合类型的成员?
【发布时间】:2013-12-01 17:04:24
【问题描述】:

我正在尝试创建一个非常简单的类来存储一棵树。我为节点创建了一个类,为树创建了一个类,它们包含在一个指针选项卡中。我的问题是我无法访问我的节点类的公共成员(我认为)。

这是我班级的代码:

#include <cmath> 
#include <iostream>
#include <cstdio>
#include <cassert>
#include <vector>


using namespace std;

template <class T>
class Node : public vector<T> {

public:
     vector<T> enfants;
     T pere; 
     T valeur; 

  Node(){valeur=T(0); pere=T(0); enfants= vector<T>();}
  Node(T v){valeur=v; pere=T(0); enfants= vector<T>();}
  Node(T v, T p) {valeur= v; pere=p; enfants=vector<T>();}     

void accouche(const T& x)
{
   enfants.push_back(x);
}



template <class T>
class Arbre: public Node<T> {

public:

      Node<T> * arbre;

      Arbre(int n){arbre= new Node<T> [n];}
      Arbre(int n, T a) {arbre= new Node<T> [n]; arbre[0]=Node<T>(a);}

void ajouter(const T& enfant, const int& posf, const T& per, const int& posp )      
{
arbre[posp].accouche(enfant);
arbre[posf]=Node<T>(enfant,per);
}


 };

这是我的主要代码

#include <cmath>
#include <iostream>
#include <cstdio>
#include <cassert>
#include <vector>
#include "classenode.hpp"


using namespace std;

int main()

{
Arbre<int> a1(4,0);

a1.ajouter(1,1,0,0);
a1.ajouter(2,2,1,1);
a1.ajouter(3,3,0,0);

cout<<a1[0].enfants.size()<<endl;
system("pause");       

}

我想得到结果“2”。但是我有这个错误

32 `enfants' has not been declared 
32  request for member of non-aggregate type before '.' token 

我尝试使用“a1[0]->enfants.size()”,但程序说基操作数不是指针。

有什么建议吗?谢谢!!

【问题讨论】:

    标签: c++ tree public


    【解决方案1】:

    a1 是一个Arbre,但a1[0] 是一个int,所以它没有任何enfants

    vector 继承通常是个坏主意;我不确定这是你的意思。

    【讨论】:

    • 你能解释一下为什么 a[0] 不是节点吗?
    • 也许我必须使用 a1.arbre[0].enfants?
    • 因为它继承自 vector&lt;int&gt;,而 [0] 为您提供了该向量的第一个元素。
    【解决方案2】:

    a1[0] 的类型是int,所以a1[0].enfants 无效。

    【讨论】:

    • 好的,我现在明白了。我的错误很愚蠢:P 非常感谢!
    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多