기타 학습/Language
[ C++ ] 객체 배열, 객체 포인터 배열
sdoaolo
2022. 5. 17. 18:14
728x90
객체도 배열로 만들 수 있다는 점
씨언어는 모든것에 포인터가 있고 배열이 있는 그런느낌이다.
객체 배열 선언
ClassName arr[10];
주의해야할 점 ❗❗
객체 배열을 선언할때도 생성자는 호출이 되기 때문에 생성자로 인자를 전달할 수 없다.
1) 다음 형태의 생성자는 정의되어있어야한다.
2) 다른 함수 형태로 일일히 값을 초기화해줄 수는 있다.
#include <iostream>
#include <string>
using namespace std;
class TestResult {
private:
int myScore;
int myNumber;
string myName;
public:
TestResult() {
myScore = 0;
myNumber = 0;
myName = "none";
}
void setInfo(int score, int number, string name);
void printAll() const;
};
void TestResult::setInfo(int score,int number,string name) {
myScore = score;
myNumber = number;
myName = name;
}
void TestResult::printAll() const {
cout << myNumber << '\n';
cout << myName << '\n';
cout << myScore << '\n';
}
int main() {
TestResult student[3];
int num, score;
string name;
for (int i = 0; i < 3; i++) {
cout << "num : " ;
cin >> num;
cout << "name : " ;
cin >> name;
cout << "score : ";
cin >> score;
student[i].setInfo(score, num, name);
}
student[0].printAll();
cout << "\n";
student[1].printAll();
cout << "\n";
student[2].printAll();
return 0;
}
객체 포인터 배열
객체 포인터 배열은 객체의 주소값 저장이 가능한 포인터 변수로 이루어진 배열
즉 객체의 주소값(포인터)이 모여있는 배열이라는 뜻
#include <iostream>
#include <string>
using namespace std;
class TestResult {
private:
int myScore;
int myNumber;
string myName;
public:
TestResult() {
myScore = 0;
myNumber = 0;
myName = "none";
}
TestResult(int score, int number, string name) {
myScore = score;
myNumber = number;
myName = name;
}
void printAll() const;
};
void TestResult::printAll() const {
cout << myNumber << '\n';
cout << myName << '\n';
cout << myScore << '\n';
}
int main() {
int num, score;
string name;
TestResult *student2[3];
for (int i = 0; i < 3; i++) {
cout << "num : ";
cin >> num;
cout << "name : ";
cin >> name;
cout << "score : ";
cin >> score;
student2[i] = new TestResult(score, num, name);
}
student2[0] -> printAll();
cout << "\n";
student2[1] -> printAll();
cout << "\n";
student2[2] -> printAll();
return 0;
}