从对象数组中打印字符串对象

问题描述 投票:0回答:1

我正在创建一个对象数组,以将每个对象分配给另一个对象数组。下面的代码包括尝试从阵列中打印对象。我的班级有一个人姓名的属性,他们可能有多少朋友的数量,以及一个用于在需要时扩展数组大小的容量变量。该类还初始化指向指针的指针,该指针旨在用于对象数组。

我想打印数组中对象的名称,以及第一个数组的每个元素指向的对象。但是,printFriends()方法不会接受我对使用的字符串变量的点运算符的使用。请参阅下面的printFriends()方法。

编译器 - G ++(Ubuntu 5.4.0-6ubuntu1~16.04.5)5.4.0。 Vim文本编辑器。错误报告在下面找到。

Person.h

class Person {
private:
  Person **friends = NULL;
  int friend_count = 0; 
  int friend_capacity = 0;
  std::string name;

public: 
  Person(std::string n) {
    friends = new Person*[100];
    friend_capacity = 100;
    for ( int i = 0; i < friend_capacity; i++ )
      friends[i] = NULL;
    name = n;
  }



void growFriends() {
  Person **tmp = friends; //Keep up with the old list
  int newSize = friend_capacity * 2; //We will double the size of the list

  friends = new Person*[newSize]; //Make a new list twice the size of original

  for (int i = 0; i < friend_capacity; i++) {
    //Copy the old list of friends to the new list.
    friends[i] = tmp[i];
  }

  delete[] tmp;  //delete the old list of friends
  friend_capacity = newSize; //update the friend count
}

void printFriends() {
  for ( int i = 0; i < friend_count; i++ )
    std::cout << friends[i].name << std::endl;
}



/*
void addFriend(const Person &obj) {
  Person **tmp = friends;
//    Person f = new std::string(obj);   

  for (int i = 0; i < friend_capacity; i++)
    friends[friend_count + 1] + obj; 

  friend_count = friend_count + 1; 
}

*/

};

与人TEST.CPP

#include<iostream>
#include"Person.h"
int main() {

Person p1("Shawn");
p1.printFriends(); 

}   

g ++ --std = c ++ 11 person-test.cpp -o p

在Person-test.cpp中包含的文件中:2:0:person.h:在成员函数中'void Person :: printFriends()':person.h:46:31:error:请求成员'name'在'( ((人)这个) - >人::朋友+((sizetype)(((long unsigned int)i)* 8ul)))',它是指针类型'Person *'(也许你打算使用' - >'?)std :: cout << friends [i] .name << std :: endl;

这个错误消息明显清楚,我理解删除错误的几种方法。一个是使用箭头符号,因为我确实使用指针。但是,这会导致分段错误。

我想通过迭代数组的元素来打印数组中的对象。我怎么能完成这个呢?使用点符号在我的程序中不起作用,如上所示,错误消息,虽然我想访问字符串以打印对象数组中的每个名称,另外每个对象数组的元素从第一个对象数组指向。

c++ arrays pointers object out-of-memory
1个回答
0
投票

friends是一个指针数组;所以friends[i]是一个指针;你需要“取消引用”才能到达成员字段:

std::cout << friends[i].name << std::endl;读起来像:

Person* friendI = friends[i];
std::cout << friendI.name << std::endl;

但你想“穿过”friendI指针;所以它需要是:

std::cout << friendI->name << std::endl;

或(没有临时变量):

std::cout << friends[i]->name << std::endl;
© www.soinside.com 2019 - 2024. All rights reserved.