CName 变量仅在构造函数方法的本地范围内声明:
Student::Student(int amount)
{
AmtClass = amount;
string *CName; // <<<
pName = new string[AmtClass]; // <<< Just leaks memory, nothing else
}
你可能打算让它成为一个类成员变量。另请注意,不需要string* 指针或new,只需使用std::vector:
class Student
{
private:
int AmtClass;
std::vector<std::string> > StudentNames;
public:
Student(int numStudents);
}
Student::Student(int numStudents)
: AmtClass(numStudents)
{
StudentNames.resize(AmtClass);
}
调用此构造函数后,您可以访问StudentNames[i],其中i 在[0-AmtClass[ 的范围内,在随后从您的Student 类中调用的方法中。
综上所述,这也建议将您的类命名为 Students 以正确反映预期的复数语义。
或者更好的是,它应该被命名为Class 持有一个std::vector<std::shared_ptr<Student> >,其中Student 应该有一个std::string 成员name。
OK, here we go:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
class Student {
private:
std::string name;
public:
Student(const std::string& name_) : name(name_) {}
const std::string& getName() const { return name; }
};
class Class {
private:
typedef std::vector<std::shared_ptr<Student>> SubscriptionList;
SubscriptionList students;
const unsigned int MaxSubscribers;
public:
Class(unsigned int maxSubscribers) : MaxSubscribers(maxSubscribers) {}
bool subscribe(std::shared_ptr<Student>& student) {
if(students.size() >= MaxSubscribers) {
return false; // Class is full, can't subscribe
}
// May be put additional checks here, to prevent multiple subscrptions
students.push_back(student);
return true; // Sucessfully subscribed the class
}
void unsubscribe(std::shared_ptr<Student>& student) {
SubscriptionList::iterator it = students.begin();
for(;it != students.end();++it) {
if(it->get() == student.get()) {
break;
}
}
students.erase(it);
}
void showSubscribedStudents(std::ostream& os) {
unsigned int i = 1;
for(SubscriptionList::iterator it = students.begin();
it != students.end();
++it, ++i) {
os << i << ". " << (*it)->getName() << std::endl;
}
}
};
int main()
{
unsigned int amount;
std::cin >> amount;
std::cin.ignore();
Class theClass(amount);
for(unsigned int i = 0; i < amount; i++)
{
std::string name;
std::getline(std::cin,name);
std::shared_ptr<Student> student(new Student(name));
theClass.subscribe(student);
}
theClass.showSubscribedStudents(std::cout);
}
输入:
5
John Doe
Jane Doe
Aldo Willis
Chuck Norris
Mia Miles
输出:
1. John Doe
2. Jane Doe
3. Aldo Willis
4. Chuck Norris
5. Mia Miles