提问者:小点点

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


null

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

编译器-G++(Ubuntu 5.4.0-6Ubuntu116.04.5)5.4.0。Vim文本编辑器。下面找到错误报告。

个人。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; 
}

*/

};

Person-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:错误:请求成员名称In(((Person)this)-&>Person::Friends+((sizetype)(((LongUnsignedInt)i)*8UL))),它是指针类型的Person*(可能您打算使用-&>?)std::cout<<;Friendsi.Name<<;std::endl;

这个错误信息非常清晰,我理解了几种删除错误的方法。一个是使用箭头表示法,因为我确实使用了一个指针。然而,这会导致分段错误。

我想通过遍历数组的元素来打印数组中的对象。我怎样才能简单地完成这件事呢?在我的程序中,使用点表示法是不起作用的,如上面显示的错误消息,尽管我希望访问字符串来打印对象数组中的每个名称,以及从第一个对象数组中指向的每个对象数组元素。


共1个答案

匿名用户

是指针数组;所以是一个指针;您需要“取消引用”它才能进入成员字段:

的内容如下:

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

但是您希望“通过”指针;所以它必须是:

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

或者(没有临时变量):

std::cout << friends[i]->name << std::endl;