c++ - 收集指针和添加对象

标签 c++ arrays pointers collections

我在向指针集合添加新对象指针时遇到了问题。我看不出我做错了什么以及为什么会出现此错误。我不确定应该如何初始化指针数组。

studenci.cpp: In constructor `Studenci::Studenci()':
studenci.cpp:10: error: expected identifier before '*' token
studenci.cpp:10: error: expected `;' before "Student"

main.cpp

#include <iostream>
#include "student.h"
#include "studenci.h"

using namespace std;

int main(int argc, char *argv[])
{


Studenci *s = new Studenci(3); //My collection

Student *s1 = new Student("s1","Adam", "Smyk", "82736372821", "s1020", 22, 1, true);  //First object
Student *s2 = new Student("s2","Arnold", "Smyk", "82736372823", "s1021", 22, 1, true);
Student *s3 = new Student("s3","Arnold", "Smyk", "82736372822", "s1031", 24, 1, false);

s1->show();
s2->show();
s3->show(); //Showing content

s->add(s1); //I think here is a problem with adding new pointers 
    s->add(s2)->add(s3);

    return 0;
}

Studenci.cpp

#include "student.h"
#include "studenci.h"
#include <iostream>
using namespace std;

Studenci::Studenci()
{
        m_tab = new *Student[m_number];  //Is it correct ? 
        m_counter = 0; 
}


void Studenci::add(Student* st)
{
    if( m_counter < m_number){

    m_tab[m_counter] = new Student(*st);  
    m_counter++;
}else
        cout<<"Full!"<<endl;    //error, no more space
}

Studenci.h

class Studenci{

    public:
    Studenci(); //default

    Studenci(int number):m_number(number)
    {} 
    public:
        int m_number;
        int m_counter;
        Student **m_tab; 

    //Function of adding
    void add(Student* st);

};

最佳答案

new *Student[m_number] 中的 * 位置错误。您正在创建一个 Student 指针数组,指针符号必须在 Student

之后
m_tab = new Student*[m_number];

关于c++ - 收集指针和添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10538281/

相关文章:

C - 带指针的字符串连接

c - 获取用户输入并存储到结构中的元素中

c++ - FFMPEG API : decode MPEG to YUV frames and change these frames

c++ - 当作为参数传递的对象超出范围时,析构函数是否会调用自身?

php - 检查关联数组是否包含键值对

c# - 将值复制到安全上下文中特定偏移量的字节数组中

c++ - 类型转换与 memcpy() : which one is better?

c++ - 如何正确使用 cin.clear 和 cin.ignore

c++ - 如何与托管在 Amazon EC2 上的 C++ 服务器通信?

Python:更改 np.array 的格式或允许 in1d 函数中的容差