c++ 공부중인데 궁금한 거 질문드립니다.
글쓴이: wsm0315 / 작성시간: 일, 2017/06/11 - 6:14오후
Student 와 School이라는 두 개의 class를 두고
School에 저장된 vector students 의 내용을
print() 함수로 출력하고 싶은데 어떻게 해야할지 모르겠네요.
어떻게 하면 students 의 내용을 출력할 수 있나요??
cout << "vector : "<< (*it)->getName << endl;
이런식으로 작성했더니 작동이 안되네요..
#include <iostream>
#include <vector>
using namespace std;
enum Grade {FRESH = 1, SOPHOMORE, JUNIOR, SENIOR};
class Student;
class School {
const string name;
vector<Student *> students;
float budget;
public:
School(const string & _name, int size = 0): name(_name), students(size) {
budget = 0;
}
void print() {
cout << name << budget << endl;
for (vector<Student *>::iterator it = students.begin(); it != students.end(); ++it) {
cout << "vector : "<< endl;
}
}
string getName() const {
return name;
}
};
class Student {
string name;
Grade grade;
const School & school;
public:
Student(const School & _school, const string & _name = "")
: school(_school) { this->name = _name; grade = FRESH; }
void print() const {
string gradeString;
switch (grade) {
case 1:
gradeString = "FRESH";
}
cout << name << grade << school.getName() << endl;
}
string getName() {
return name;
}
};
int main(void)
{
School school("Busan", 1);
Student a(school, "sumin");
school.print();
a.print();
Grade grade;
grade = static_cast<Grade>(2);
}Forums:


소스코드를 code 태그 안에 넣어서 질문하셔요.
소스코드를 code 태그 안에 넣어서 질문하셔요.
세벌 https://sebuls.blogspot.kr/
제가 처음해봐서 그런게 있었네요. 감사합니다.
제가 처음해봐서 그런게 있었네요. 감사합니다.
흠.
cout << "vector : "<< (*it)->getName() << endl;그건 그렇고 School에 Student를 넣는 코드가 안 보이는데 잘라서 올려주신거죠?
참고해보세요.
링크' 걸린 부분의 실행 되는 코드만. 보시면 됩니다.
http://codepad.org/6OixoKfz
#include <iostream> #include <vector> using namespace std; class CTest { string m_name; public: CTest(){} ~CTest(){} void fn_set(string name) { m_name = name; } void fn() { cout << m_name << endl; } }; class CMain { public: CMain(){} ~CMain() { m_v.clear(); }; vector<CTest> m_v; void fn_push(CTest ct) { m_v.push_back(ct); } void fn(){ cout << "main" << endl; } void fn_list() { for (std::vector<CTest>::iterator it = m_v.begin() ; it != m_v.end(); ++it) { CTest ct = (CTest) *it; ct.fn(); //cout << ct.fn() << endl; 웹에서는 이부분이 오류발생함. } } }; int main() { CTest ct1; CTest ct2; vector<CTest> v; ct1.fn(); ct2.fn(); v.push_back(ct1); v.push_back(ct2); v[0].fn(); v[1].fn(); //http://www.cplusplus.com/reference/vector/vector/begin/ for (std::vector<CTest>::iterator it = v.begin() ; it != v.end(); ++it) { CTest ct = (CTest) *it; ct.fn(); //cout << ct.fn() << endl; 웹에서는 이부분이 오류발생함. } CMain cm; ct1.fn_set("test1"); ct2.fn_set("test2"); cm.fn_push(ct1); cm.fn_push(ct2); cm.fn_list(); //http://ruvendix.blog.me/221015795188 v.clear(); return 0; } //출력결과 test1 test2//
웹에서 컴파일 할때.
cout << ct.fn() << endl; 웹에서는 이부분이 오류가 발생합니다.
ct.fn(); 으로 cout 없이. 사용 하시기 바랍니다.
//
웹에서 컴파일 할때. switch()사용시. default: break; 를 적어주셔야 합니다.
switch (grade) { case 1: break; default: break; }//---------------------------------
//이런 문제가 발생했다면?
//---------------------------------
//t.cpp: In member function 'void School::print()':
//Line 25: error: invalid use of undefined type 'struct Student'
//compilation terminated due to -Wfatal-errors.
//t.cpp: In member function 'void School::print()':
//Line 24: error: request for member 'getName' in 'pSt', which is of non-class type 'Student*'
//compilation terminated due to -Wfatal-errors.
//Student 클래스가 선언만 되어 있는 경우. 클래스를 구조체로 인식하여.
//웹에서 컴파일 오류가 발생합니다.
//함수 정의 구현부에서 클래스 참조를 못하여. 컴파일이 안됩니다.
//그럴때는. 함수 정의 구현부'를 클래스 헤더의 아래로 옮겨주어 해결합니다.
class CSchool { void fn_push(CStudent & st); //이것이 선언 }; void CSchool::fn_push(CStudent & st) //이것이 정의 구현부 (를 클래스들의 맨 아래코드로 이동) { m_students.push_back(&st); }이렇게 웹에서 컴파일은 어떻게... 되었습니다.
그렇지만. vector 값을 얻어올때. Segment Fail 오류가 발생합니다. ㅇ_ㅇ;;
이 오류에 대해. 저도 원인을 잘 모르겠네요.
그러니. 먼저 알려드린 코드는 잘 되니. 그것을 참고하시기 바랍니다.
//
다시 코드를 확인해보니. 생성자 변수 초기화'에 숫자 값이 입력되었네요.
제거해 줍니다.
//
vector<변수> 도 int. void. void*. CStudent*. 는 되는데. CStudent 는 안되네요.
생성자 변수 초기화' 때문이었나? ㅇ_ㅇ?? 확인해봐야 합니다. 일단. 주소'값을 사용했습니다.
//-----------------------
//이제 다시 해보니. 됩니다.
//-----------------------
http://codepad.org/InJpnxTV
#include <iostream> #include <vector> using namespace std; enum Grade {FRESH = 1, SOPHOMORE, JUNIOR, SENIOR}; class CStudent; class CSchool { const string name; float budget; public: vector<void*> m_students; CSchool(const string & _name, int size = 0): name(_name) { budget = 0; } ~CSchool() { m_students.clear(); } void fn_push(CStudent & st); void fn_push(CStudent * pst); void print(); string getName() const { return name; } }; class CStudent { string name; Grade grade; const CSchool & school; public: CStudent(const CSchool & _school, const string & _name = "") : school(_school) { this->name = _name; grade = FRESH; } ~CStudent() { } void print() const { string gradeString; switch (grade) { case 1: gradeString = "FRESH"; break; default: break; } cout << name << grade << school.getName() << endl; } string getName() { return name; } }; //Student 클래스가 선언만 되어 있는 경우. 클래스를 구조체로 인식하여. //웹에서 컴파일 오류가 발생합니다. //함수 정의 구현부에서 클래스 참조를 못하여. 컴파일이 안됩니다. //그럴때는. 함수 정의 구현부'를 클래스 헤더의 아래로 옮겨주어 해결합니다. void CSchool::fn_push(CStudent & st) { // m_students.push_back(&st); cout << "[1]" << endl; //string n1 = (*m_students[0]).getName(); //정상 실행. //string n2 = st.getName(); //정상 실행. cout << "[2]" << endl; //cout << n1 << endl; cout << "[3]" << endl; //cout << n2 << endl; cout << "[4]" << endl; } void CSchool::fn_push(CStudent * pst) { m_students.push_back((void*)pst); cout << m_students[0] << endl; CStudent * p = (CStudent *) m_students[0]; string n = p->getName(); cout << "[push] " << n << endl; } //t.cpp: In member function 'void School::print()': //Line 25: error: invalid use of undefined type 'struct Student' //compilation terminated due to -Wfatal-errors. //t.cpp: In member function 'void School::print()': //Line 24: error: request for member 'getName' in 'pSt', which is of non-class type 'Student*' //compilation terminated due to -Wfatal-errors. void CSchool::print() { cout << name << budget << endl; for (vector<void*>::iterator it = m_students.begin(); it != m_students.end(); ++it) { cout << "[x]" << endl; CStudent * pSt = (CStudent *)*it; cout << "[x]" << endl; string name = (pSt)->getName(); cout << "[x]" << endl; cout << name << endl; } } int main(void) { CSchool school("Busan", 10); // CStudent a(school, "sumin"); // CStudent b(school, "sumin2"); CStudent * pa = new CStudent(school, "sumin"); CStudent * pb = new CStudent(school, "sumin2"); school.fn_push(pa); school.fn_push(pb); school.print(); pa->print(); Grade grade; grade = static_cast<Grade>(2); delete pa; delete pb; pa = NULL; pb = NULL; } //출력 결과 0x833d498 [push] sumin 0x833d498 [push] sumin Busan0 [x] [x] [x] sumin [x] [x] [x] sumin2 sumin1Busan//-------------------------
//다시 해보니. 클래스 인스턴스'로도 되네요. 안되서 new로 만들었는데... ㅇ_ㅇ;;
//그래도. 메모리 확인은 별도로 해보시기 바랍니다.
//-------------------------
http://codepad.org/ir4bjDON
#include <iostream> #include <vector> using namespace std; enum Grade {FRESH = 1, SOPHOMORE, JUNIOR, SENIOR}; class CStudent; class CSchool { const string name; float budget; public: vector<void*> m_students; CSchool(const string & _name, int size = 0): name(_name) { budget = 0; } ~CSchool() { m_students.clear(); } void fn_push(CStudent & st); void print(); string getName() const { return name; } }; class CStudent { string name; Grade grade; const CSchool & school; public: CStudent(const CSchool & _school, const string & _name = "") : school(_school) { this->name = _name; grade = FRESH; } ~CStudent() { } void print() const { cout << "CStudent" << endl; string gradeString; switch (grade) { case 1: gradeString = "FRESH"; break; default: break; } cout << name << grade << school.getName() << endl; } string getName() { return name; } }; //Student 클래스가 선언만 되어 있는 경우. 클래스를 구조체로 인식하여. //웹에서 컴파일 오류가 발생합니다. //함수 정의 구현부에서 클래스 참조를 못하여. 컴파일이 안됩니다. //그럴때는. 함수 정의 구현부'를 클래스 헤더의 아래로 옮겨주어 해결합니다. void CSchool::fn_push(CStudent & st) { m_students.push_back(&st); } //t.cpp: In member function 'void School::print()': //Line 25: error: invalid use of undefined type 'struct Student' //compilation terminated due to -Wfatal-errors. //t.cpp: In member function 'void School::print()': //Line 24: error: request for member 'getName' in 'pSt', which is of non-class type 'Student*' //compilation terminated due to -Wfatal-errors. void CSchool::print() { cout << "CSchool" << endl; cout << name << budget << endl; for (vector<void*>::iterator it = m_students.begin(); it != m_students.end(); ++it) { cout << "[x]" << endl; CStudent * pSt = (CStudent *)*it; cout << "[x]" << endl; string name = (pSt)->getName(); cout << "[x]" << endl; cout << name << endl; } } int main(void) { CSchool school("Busan", 10); CStudent a(school, "sumin"); CStudent b(school, "sumin2"); school.fn_push(a); school.fn_push(b); school.print(); a.print(); b.print(); Grade grade; grade = static_cast<Grade>(2); } //출력 결과 CSchool Busan0 [x] [x] [x] sumin [x] [x] [x] sumin2 CStudent sumin1Busan CStudent sumin21Busan----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.
매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.
각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com
댓글 달기