C++ 나만 이러는거야??

@Super_E끌림·2025년 10월 25일

이번 시험을 보면서 나만의 C++에서 고질적인 문제를 발견했다.
시험을 포함해서 2번째이다.

먼저 문제의 코드를 보겠습니다.(시험 소스코드 유출을 방지하기 위해 임의로 작성한 것입니다.)
삼각형 넓이를 클래스를 이용해 각 변의 2를 더해 구하는 문제라고 가정합니다.

#include <iostream>

using namespace std;

class Triangle{
	int height;//높이
    int bottom;//밑변
public:
	Triangle(int a, int b);
	void Add();
	double getArea();
};

Triangle::Triangle(int a, int b){
	height = a;
    bottom = b;
}

void Triangle::Add(){
	height += 2;
    bottom += 2;
}

double Triangle::getArea(){
	return height * bottom * 0.5
}

int main(){
	Triangle tri(10,2);
    tri.Add();
    cout<<"삼각형 넓이: "<<tri.getArea()<<endl;
}

이 코드 작성 할때도 나도 모르게 작성하고 있었닼 ㅋㅋㅋ 하.. ㅋ
완벽한 코드다.
그럼 이번에는 저의 문제되는 코드를 보여드리겠습니다.(?)

#include <iostream>

using namespace std;

class Triangle{
	int height;
    int bottom;
public:
	Triangle(int a, int b);
	void Add();
	double getArea();
};

Triangle::Triangle(int a, int b){
	int height = a;//???
    int bottom = b;//???
}

void Triangle::Add(){
	height += 2;
    bottom += 2;
}

double Triangle::getArea(){
	return height * bottom * 0.5
}

int main(){
	Triangle tri(10,2);
    tri.Add();
    cout<<"삼각형 넓이: "<<tri.getArea()<<endl;
}

고질적인 그 문제는 바로 생성자 함수에 변수를 한 번 더 선언 해버립니다...???
왜 이러는지는 모르겠지만 C에서 함수는 다른 지역 변수라 초기화 하는 습관 때문인지 생각해보면
Add()getArea()에서도 선언을 해야 하는데 왜 생성자에만.. 다행이라 해야 할지.. 아니라 해야 할지..

profile
SoC:) SoC:)

0개의 댓글