객체 배열 및 객체 포인터 배열은 구조체 배열과 구조체 포인터 배열과 비슷하다.
SoSimple arr[10];
형태로 선언
동적할당 할 경우SoSimple * ptrArr = new SoSimple[10];
형태로 선언
#include <iostream>
#include <cstring>
using namespace std;
#pragma warning(disable:4996)
class Person
{
private:
char* name;
int age;
public:
Person(char* myname, int myage) {
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
Person()
{
name = NULL;
age = 0;
cout << "called Person()" << endl;
}
void SetPersonInfo(char* myname, int myage)
{
name = myname;
age = myage;
}
void ShowPersonInfo() const
{
cout << "이름: " << name << ", ";
cout << "나이: " << age << endl;
}
~Person()
{
delete[] name;
cout << "called destructor" << endl;
}
};
int main()
{
Person parr[3]; // 객체 배열 선언
char namestr[100];
char* strptr;
int age;
int len;
for (int i = 0; i < 3; i++)
{
cout << "이름: ";
cin >> namestr;
cout << "나이: ";
cin >> age;
len = strlen(namestr) + 1;
strptr = new char[len]; // name이 들어갈 동적메모리 할당
strcpy(strptr, namestr);
parr[i].SetPersonInfo(strptr, age); // parr[0] ~ parr[2]까지 접근
}
for (int i = 0; i < 3; i++)
{
parr[i].ShowPersonInfo();
}
return 0;
}
포인터일땐 '->' 사용해서 접근해야한다
#include <iostream>
#include <cstring>
using namespace std;
#pragma warning(disable:4996)
class Person
{
private:
char* name;
int age;
public:
Person(char* myname, int myage) {
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
Person()
{
name = NULL;
age = 0;
cout << "called Person()" << endl;
}
void SetPersonInfo(char* myname, int myage)
{
name = myname;
age = myage;
}
void ShowPersonInfo() const
{
cout << "이름: " << name << ", ";
cout << "나이: " << age << endl;
}
~Person()
{
delete[] name;
cout << "called destructor" << endl;
}
};
int main()
{
Person* parr[3]; // 객체 포인터 배열 선언
char namestr[100];
int age;
for (int i = 0;i < 3;i++)
{
cout << "이름: ";
cin >> namestr;
cout << "나이: ";
cin >> age;
parr[i] = new Person(namestr, age);
}
parr[0]->ShowPersonInfo();
parr[1]->ShowPersonInfo();
parr[2]->ShowPersonInfo();
delete parr[0];
delete parr[1];
delete parr[2];
return 0;
}
#include <iostream>
using namespace std;
class TwoNumber
{
private:
// 멤버변수
int num1;
int num2;
public:
TwoNumber(int num1, int num2) // 매개변수
{
this->num1 = num1; // num1(멤버변수) = num1(매개변수)
this->num2 = num2;
}
void ShowTwoNumber()
{
cout << this->num1 << endl; // this -> num1 : 멤버변수
cout << this->num2 << endl;
}
};
int main()
{
TwoNumber two(2, 4);
two.ShowTwoNumber();
return 0;
}
#include <iostream>
using namespace std;
class SelfRef
{
private:
int num;
public:
SelfRef(int n) : num(n)
{
cout << "객체생성" << endl;
}
SelfRef& Adder(int n)
{
num += n;
return *this;
}
SelfRef& ShowTwoNumber()
{
cout << num << endl;
return *this;
}
};
int main()
{
SelfRef obj(3);
SelfRef& ref = obj.Adder(2);
obj.ShowTwoNumber();
ref.ShowTwoNumber();
ref.Adder(1).ShowTwoNumber().Adder(2).ShowTwoNumber();
return 0;
}