직접참조 연산자: . (객체가 멤버에 접근하기 위해 사용)
// 배열 원소
int main(void)
{
int num[3]; //배열 선언시 첨자의 값은 배열의 크기
num[0]=10;
num[1]=20;
num[2]=30;
std::cout << num[0] << num[1] << num[2] << std::endl;
return 0;
}
// 배열 원소
int main(void)
{
int han[10] = {10,20};
int han1[2] = {10,20};
// 배열의 초기화 / 배열이 다 0으로
int han2[10] = {0};
// han[0] == &han[0] 배열의 이름은 배열의 주소값과 동일하다
std::cout << han[0] << " " << &han[0] << std::endl;
std::cout << han2[0] << " " << &han2[0] << std::endl;
return 0;
}
#include 혹은 #include <string.h> 필수!
int main(void){
char s1[5];
char s2[5] = "soft"; //원본
// s1=s2; // 에러
// null 문자가 나올 때 까지 copy해라
strcpy(s1,s2); //s2 주소의 문자열을 s1주소로 복사
std::cout << "s1=" << s1 << " s2=" << s2 << std::endl;
return 0;
}
int main(void)
{
std::string s1;
std::string s2 = "soft";
s1 = s2; //string 복사는 그냥 대입
//strcpy(s1,s2);
std::cout << "s1=" << s1 << " s2=" << s2 << std::endl;
return 0;
}
std::string vending(int x)
//const char* vending(int x)와도 같은 결과값
{
if (x == 1) return "커피";
else return "유자차";
}
int main()
{
std::cout << vending(1) << std::endl;
return 0;
}
class Cat {
private: //생략가능
int age;
char name[20]; // A
// std::string name;
public:
int getAge();
const char * getName();
//std::string getName();
void setAge(int a);
void setName(const char *pName);
// void setName(std::sting pName);
};
int Cat::getAge()
{
return age;
}
void Cat::setAge(int a)
{
age = a;
}
void Cat::setName(const char *pName)
// void Cat::setName(std::sting pName)
{
strcpy(name, pName);
}
const char * Cat::getName()
// std::string Cat::getName()
{
return name;
}
int main()
{
Cat nabi;
nabi.setName("나비");
nabi.setAge(3);
std::cout << nabi.getName() << " 나이는" << nabi.getAge() << "살이다." << std::endl;
return 0;
}
class Dog {
private:
int age;
public:
int getAge() {return age;}
void setAge(int a) {age = a;}
};
int main()
{
Dog happy, *pd; //일반객체 happy와 포인터 객체 pd, int x, *px;
pd = &happy; //px=&x; pd는 happy의 주소값을 가져온다.
happy.setAge(5); //일반객체는 '.'으로 멤버 접근
// 화살표가 있으면 일반객체가 아니고 포인터 객체이다
std::cout << pd -> getAge() << happy.getAge() << std::endl; //포인터 객체는 '->'로 멤버를 접근
pd -> setAge(3);
std::cout << pd->getAge() << happy.getAge(); //포인터 객체는 '->'로 멤버를 접근
return 0;
}
class Dog {
private:
int age;
public:
int getAge() {return age;}
void setAge(int a) {age = a;}
};
int main()
{
Dog dd[5];
Dog *pd;
pd=dd; //배열의 이름은 그 배열의 시작주소이다.
for (int i=0; i<5; i++){
pd->setAge(i);
std::cout<<dd[i].getAge()<<std::endl;
std::cout<<&dd<<std::endl; //
std::cout<<pd->getAge()<<std::endl;
std::cout<<&pd<<std::endl;
pd++;
}
return 0;
}
// 결과값
// 0 0x7ffdcf6dd080
// 0 0x7ffdcf6dd078
// 1 0x7ffdcf6dd080
// 1 0x7ffdcf6dd078
// 2 0x7ffdcf6dd080
// 2 0x7ffdcf6dd078
// 3 0x7ffdcf6dd080
// 3 0x7ffdcf6dd078
// 4 0x7ffdcf6dd080
// 4 0x7ffdcf6dd078