【问题标题】:Add objects to a vector pointed to by another object of the same class将对象添加到由同一类的另一个对象指向的向量
【发布时间】:2020-07-23 12:02:09
【问题描述】:

作为 C++ 任务的一部分,以了解有关指针和对象的更多信息,我有一个代表家庭成员的类。其中一个参数是向量指针“kids”,它应该包含同一类的对象。我被告知要使用带有“

#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;

class Family{
public: 
   string name; 
   int age; 
   //An object pointer of Family to represent a spouse 
   Family * spouse; 
   //a vector pointer of Family to represent children 
   vector<Family>* kids;

   /** 
   * A constructor that takes 4 arguments 
   * @param n  takes default 'unknown' 
   * @param a  takes default 18
   * @param s  takes default NULL
   * @param v  takes default NULL
   */ 
   Family( string n="Unknown", int a=18, Family * s=NULL,vector<Family> * v=NULL){
       name=n; 
       age=a; 
       kids=new vector<Family>; 
       spouse=s; 
   }
   /**2pts
    * Create a method that overloads < 
    * The method will add a Family object to the list of children
    * @param a Family object 
    */
   int kCount = 0;
   void operator<(Family f) {
       (*kids)[kCount] = f;
   }
};
int main(int argc, char** argv) {
    //Declaring an object F using a name and age=35 representing a female.
      Family F("Nicky",35);
    //Declaring an object M using a name, age =39 and spouse being the previous object
      Family  M("Nick",39,&F);

    Family c0("Ricky", 15);
    Family c1("Bicky", 12);
    Family c2("Dicky", 9);
    Family c3("Micky", 6);
    //2pts Add the kids to M using the operator <
    M < c0; 
    return 0;
}

当我尝试运行它时,我得到一个段错误。我对指针还是很缺乏经验,所以我真的不知道如何解决这个问题。

【问题讨论】:

  • 使用operator&lt; 插入对象是相当晦涩的。使用operator&lt;&lt; 更为常见,尽管您需要使用您被告知要使用的内容。您可能需要重新检查 vector 的文档以了解如何将元素添加到向量。
  • 为什么你的向量对象是指针?您希望通过使其成为一个指针来完成什么,必须显式分配和解除分配,所有额外的工作,这对您有什么作用(这与导致此崩溃的简单错误没有直接关系,但它增加了不必要的语法和复杂性,从而混淆了潜在的问题)?
  • 山姆,我真希望我知道。我的教授……很有趣。我只需要尽力而为。
  • 只是澄清一下:您的教授是否明确指示您使用指针,您的教授的指示到底是什么?当然,您的教授很可能是不称职的 C++ 讲师,这里有大量证据表明不称职的 C++ 讲师,但您也很可能只是误解了某些东西。

标签: c++ pointers vector operator-overloading


【解决方案1】:

根据一位评论者的提示,我查找了一些有关将对象添加到向量的信息并找到了解决方案。

void operator<(Family f) {
    (*kids).push_back(f);
}

// in main()...

Family c0("Ricky", 15);
M < c0;

感谢 1201ProgramAlarm 的提示!

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多