<객체의 멤버 호출과 재사용 단위 : 오류 찾기>
#include <iostream> using std::cout; class Dog { private: int age; public: int getAge(); void setAge(int a); }; int Dog::getAge() { return age; } void Dog::setAge(int a) { age = a; } int main() { Dog happy; <Dog class의 happy객체 정의> //Dog.age = 2; <① Dog는 class이므로 이 줄은 삭제> happy.age=3; <② age는 private멤버로 클래스 밖에서 접근 불가><변경→ happy.setAge(3);> cout<<happy.age; <③ age는 전용멤버로 접근 불가> <변경→ cout << happy.getAge();> return 0; }
<Dog클래스와 happy객체(인스턴스)>
#include <iostream> using namespace std; class Dog { private: int age; double weight; string name; public: int getAge() { return age; } void setAge(int a) { age = a; } double getWeight() { return weight; } void setWeight(double w) { weight = w; } string getName() { return name; } void setName(string n) { name = n; } }; int main() { Dog happy; happy.setAge(3); happy.setWeight(3.5); happy.setName("해피"); cout << happy.getName() << "는 " << happy.getAge() << "살, " << happy.getWeight() << "kg입니다.\n"; return 0; }