object
클래스는 반올림 연산자 인 ==
과 !=
연산자를 제외하고 C++로 잘 작성되었습니다. 나는 다음과 같이 2 개의 객체를 가지고 시도했다. 둘 다 5
으로 초기화되었다. ==
연산자를 사용하는 경우 그러나, 그것은 (5
) 둘 다 0x00000005
을 포함, 나는 ==
연산자를 테스트 라인에 중단 점을 설정하는 경우에도 불구하고, (!=
와 true
) false
를 반환합니다. 나는 내 코드에 어떤 문제가 있는지 확실하지 않다 :C++ object [implementation] operator == error
class object
{
private:
class dummy
{
public:
dummy(){}
virtual ~dummy(){}
virtual dummy *duplicate() const = 0;
virtual const std::type_info &type() const = 0;
void *address;
};
template < typename _Ty > class data : public dummy
{
friend class object;
public:
data(const _Ty &_Value) : __inner(_Value){}
~data(){}
const std::type_info &type() const
{
return typeid(_Ty);
}
data *duplicate() const
{
return new data<_Ty>(__inner);
}
private:
_Ty __inner;
};
dummy *d;
public:
object()
{
d->address = NULL;
}
template < typename _Ty > object(const _Ty &_Value) : d(new data<_Ty>(_Value))
{
d->address = reinterpret_cast<void *>(_Value);
}
object(object &_Rhs) : d(_Rhs.d->duplicate()){}
~object()
{
if (has_value())
{
d->~dummy();
}
}
const std::type_info &type() const
{
return d->type();
}
template < typename _Ty > _Ty cast() const
{
if (typeid(_Ty) != type())
{
throw std::exception("");
}
return reinterpret_cast< data<_Ty> *>(d)->__inner;
}
const object &operator=(object &_Rhs)
{
d = _Rhs.d->duplicate();
return *this;
}
template < typename _Ty > const object &operator=(const _Ty &_Value) const
{
d = new data<_Ty>(_Value);
d->address = reinterpret_cast<void *>(_Value);
return *this;
}
template < typename _Ty > bool operator==(const _Ty &_Value) const
{
return (type() != typeid(_Ty) ? false : cast<_Ty>() == _Value);
}
bool operator==(object &_Rhs) const
{
return (type() != typeid(_Rhs.type()) ? false : d->address == _Rhs.d->address);
// Breakpoint tested above ^^^
}
template < typename _Ty > bool operator!=(const _Ty &_Value) const
{
return (type() == typeid(_Ty) ? false : cast<_Ty>() != _Value);
}
bool operator!=(object &_Rhs) const
{
return !(*this == _Rhs);
}
bool has_value() const
{
return !!d;
}
bool empty() const
{
return !d;
}
};
int main()
{
object a = 5, b = 5;
std::cout << std::boolalpha
<< (a == b);
getchar();
}
개체 유형은 부스트처럼 날 것으로 보인다 :: 하나를. 당신의 목표는 무엇입니까? 어떤 것과 같은 동적 유형을 구현하거나 고전적인 OOP 슈퍼 루트를 작성 하시겠습니까? – Manu343726
수업이 상당히 엉망입니다. 예를 들어, Object() 이니셜 라이저는 'd-> address = NULL'을 설정하지만 첫 번째 위치에서는 'd'포인터를 초기화하지 않습니다. d = 새 데이터(); 객체의 생성자 및 삭제 D; 오브젝트 소멸자에서 더 틀릴 수도 있습니다. – pscs
@Joseph - 목표가 C++처럼 보이게하거나 자바처럼 작동하도록하지 마십시오. – PaulMcKenzie