我想创建一个文件,在其中我可以将Person添加到PersonList,包括一个计数器,确保不超过PersonList的容量。我评论了所有功能,以明确他们应该执行的任务。
在编译期间,我收到以下错误:
invalid use of non-static data member 'PersonList::m_Capacity'
不幸的是我无法弄清楚代码中的错误:
的main.cpp
#include <iostream>
#include "Person.h"
#include "PersonList.h"
int main()
{
Person p1 = Person("John", 21);
Person p2 = Person("Elham", 19);
PersonList p_list = PersonList();
p_list.add(p1);
p_list.add(p2);
std::cout << p_list.get_Size() << std::endl;
Person p = p_list.get(0);
std::cout << p.get_Name() << " " << p.get_Age() << std::endl;
return 0;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
class Person
{
public:
Person();
Person(std::string Name, int Age);
void set_Name(std::string name);
void set_Age(int age);
std::string get_Name();
int get_Age();
private:
std::string m_Name;
int m_Age;
};
#endif // PERSON_H
Person.cpp
#include <string>
#include "Person.h"
Person::Person(){}
Person::Person(std::string Name, int Age){
// pre: 0 <= Age
// post: m_Name, if pre Name (is true) Age = m_Age,
// otherwise age = -1
set_Name(Name);
if (0 <= Age){
set_Age(Age);
}
else{
set_Age(-1);
}
}
void Person::set_Name(std::string Name){
// post: m_Name = Name
m_Name = Name;
}
void Person::set_Age(int Age){
// pre: 0 <= Age
// post: if pre Age (is true) = m_Age, otherwise m_Age = -1;
if (0 <= Age){
m_Age = Age;
}
else set_Age(-1);
}
std::string Person::get_Name(){
// post: returns name
return m_Name;
}
int Person::get_Age(){
// post: returns age
return m_Age;
}
PersonList.h
#ifndef PERSONLIST_H
#define PERSONLIST_H
class PersonList
{
public:
PersonList();
void add(Person p);
void set_Size(int Size);
int get(int index);
int get_Size();
private:
const int m_Capacity;
const Person m_Empty;
Person m_Data[m_Capacity];
int m_Size;
};
#endif // PERSONLIST_H
PersonList.cpp
#include "Person.h"
#include "PersonList.h"
PersonList::PersonList()
m_Capacity(10), m_Empty(Person())
{
// post: has created a new PersonList-object with
// CAPACITY elements and size = 0
set_Size(0);
}
void PersonList::add(Person p){
// pre: size < CAPACITY
// post: if pre (is true) p has been stored at the
// first empty location. size was incremented.
if (m_Size < m_Capacity){
m_Data[m_Size] = p;
set_Size(m_Size+1);
}
}
void set_Size(int Size){
m_Size = Size;
}
int PersonList::get(int index){
// pre: 0 <= index && index < size
// post: if pre returns data[index] otherwise returns EMPTY
if (0 <= index && index < m_Size){
return m_Data[index];
}
else{
return m_EMPTY;
}
}
int PersonList::get_Size(){
// post returns size;
return m_Size;
}
答案 0 :(得分:5)
C ++不支持变长数组(VLA),这就是您所拥有的:
Person m_Data[m_Capacity];
为此,m_Capacity
必须是编译时常量。
除此之外,您的默认构造函数中存在语法错误,其中需要:
来指示初始化列表:
PersonList::PersonList() : m_Capacity(10), m_Empty(Person()) { .... }
// ^ Here!
答案 1 :(得分:0)
构造函数和初始化列表必须用冒号分隔。喜欢这个
PersonList::PersonList() : m_Capacity(10), m_Empty(Person())