"캐스팅 - 플로트"방식을 정의 할 때 대답을 진행할 수 있지만 추가 기능을 구현하기 위해 공용 API를 사용하기 시작하는 것이 더 바람직하다고 생각합니다.
일반적으로 간단한 "캐스팅"은 트릭을 수행하지 않습니다 (예 : MyFloat
이 MyMatrix
일 경우 어떻게됩니까?).
아래의 접근법은 분명히 더 장황하지만, "자신의 음식을 먹어야 함"을 강조합니다. 즉, 모호한 묵시적 캐스트가 아니라 자신의 공용 인터페이스를 기반으로하는 추가 동작을 구현해야한다는 것을 강조합니다. 또는 friend
함수. 자체 API를 사용하는 경우 : 제한 사항을 이해하고 수정할 경우 기본 클래스의 재 컴파일을 잠재적으로 저장할 수 있습니다.
또한 클래스에 대한 액세스를 계산하거나 기본 값에 대한 액세스를 제어하려는 경우 : 코드를 operator float()
및 float value()
에 복제해야하는 캐스팅 연산자를 사용한다고 가정합니다.
여기 내 겸손한 제안은 길지만 내 취향에 따라 OO 디자인 원칙을 잘 반영합니다. (g++ example.cpp -Wall -Wextra
컴파일)
#include<iostream>
class MyFloat {
public:
MyFloat(float value):
m_value(value) { }
float value() const {
return m_value;
}
private:
float m_value;
};
// Eat your own food: implement functions using your public interface
// until proven need to do otherwise. This will help you assess the
// usability of your API.
float operator+(const MyFloat& lhs, const MyFloat& rhs) { return lhs.value() + rhs.value(); }
float operator+(const MyFloat& lhs, float rhs) { return lhs.value() + rhs; }
float operator+(float lhs, const MyFloat& rhs) { return lhs + rhs.value(); }
// See, now I can define another operator without need to recompile my
// class (this could have been placed in another file)
std::ostream& operator<<(std::ostream& os, const MyFloat& mf) {
os<<"MyFloat("<<mf.value()<<")";
return os;
}
int main() {
MyFloat x = 3.5; // would not work if I had declared the constructor as "explicit"
MyFloat y = x + 3.2;
MyFloat z = 3.4 + y;
std::cout<<x<<", "<<y<<", "<<z<<std::endl;
}
출력 :
MyFloat(3.5), MyFloat(6.7), MyFloat(10.1)
당신은'가 +'비 멤버 함수를 확인해야합니다. –
비회원 연산자 오버로드를 만들 수 있습니다. – IdeaHat
C++에서 연산자 오버로드를 수행 한 지 오래되었지만 'MyFloat operator + (float x) {return num + x; }'? 그는 'MyFloat' 인스턴스에 네이티브'float'을 추가하고 있습니다. – crush