C++

C++ 프로그래밍 6주차

asd135 2023. 10. 18. 12:45
728x90

구조체 클래스로 바꾸기

#include <iostream>
struct Man
{
	int age;
	double weight;
};
int main()
{
	Man han;
	han.age = 1; 
	han.weight = 54.05;
	std::cout << han.age << std::endl << han.weight;
}

 

에러.1

#include <iostream>
class Man
{
	int age;
	double weight;
};
int main()
{
	Man han;
	han.age = 1; // error C2248: 'Man::age': private 멤버('Man' 클래스에서 선언)에 액세스할 수 없습니다.
	han.weight = 54.05; // error C2248: 'Man::weight': private 멤버('Man' 클래스에서 선언)에 액세스할 수 없습니다.
	std::cout << han.age << std::endl << han.weight;
}

수정

#include <iostream>
class Man
{
public:
	int age;
	double weight;
};
int main()
{
	Man han;
	han.age = 1; 
	han.weight = 54.05;
	std::cout << han.age << std::endl << han.weight;
}

구조체의 기본 제어 접근 속성: public 

클래스의 기본 제어 접근 속성: private

클래스는 private이 기본 값 public으로 바꿔야 클래스 외부에서 접근 가능함

 


기본적인 클래스 구조

1번째 방법으로 객체를 생성하는 방식은 잘 안 쓴다.

 


프로그래밍 언어 접근 속성

밑줄 그어진 부분은 기본 접근 속성이므로 생략가능

 


private

 

public

 

protected

#include <iostream>
class Dog
{
private:
	int age;
	double weight;

public:
	void setAge(int age) { this->age = age; }
	int getAge() { return this->age; }
	void setWeight(double weight) { this->weight = weight; }
	double getWeight() { return this->weight; }

};
int main()
{
	Dog d;
	d.setAge(5);
	d.setWeight(10.5);
	std::cout << d.getAge() << "살 " << d.getWeight() << "kg";
}

클래스 다이어 그램

private:

public: +

 


클래스 외부에 함수정의

class Dog
{
private:
	int age;
	double weight;

public:
	void setAge(int age); // 함수선언
	int getAge();
	void setWeight(double weight);
	double getWeight();
};

void Dog::setAge(int age) { this->age = age; } // 함수정의
int Dog::getAge() { return this->age; }
void Dog::setWeight(double weight) { this->weight = weight; }
double Dog::getWeight() { return this->weight; }



int main()
{
	Dog d;
	d.setAge(5);
	d.setWeight(10.5);
	std::cout << d.getAge() << "살 " << d.getWeight() << "kg";
}

외부에 함수 정의 하는 방법

반환타입 클래스이름::함수이름() { }

 

 

 

 

 


 inline 함수

중요

 

 

이 소스들은 한성현 교수님의 소스를 일부 편집, 수정하여 만들었습니다.