개발
임시 객체 활용
jmob_blog
2019. 11. 9. 01:26
728x90
반응형
#include <iostream>
#include <cstdlib>
using namespace std;
// template<typename T> T* memAlloc(int sz, T)
// {
// return (T*)malloc(sz);
// }
class memAlloc
{
int size;
public:
inline memAlloc(int sz) : size(sz) {}
template<typename T>operator T*()
{
return (T*)malloc(size);
}
};
int main(void)
{
double* p = memAlloc(40); // class name() : 임시객체...
// 임시객체.operator double*()
int* p2 = memAlloc(40);
cout << "Hello Goorm" << endl;
}
#include <iostream>
using namespace std;
int main()
{
int n = 0 ; // 'a'
cin >> n ; // 'a'
if (cin.fail())
cout << "fail" << endl;
if (cin) // if (bool, 정수, 실수, pointer)...
// cin.operator void*() => C++98/03
// cin.operator bool() => c++11
cout << "success" << endl ;
}
#include <iostream>
using namespace std;
//void true_function();
class istream // basic_istream
{
public :
bool fail() { return false ;}
// 1. bool로 변환 , 단점 shift 연산이 허용된다.
operator bool() {return fail() ? false : true ;}
// 2. void* 로 변환
operator void*() { return fail() ? 0 : this ; }
// 3. 함수 포인터로 변환
typedef void(*F)();
operator F() { return fail() ? 0 : &true_function;}
// 4. 맴버 함수 포인터로의 변환 -> safe BOOL 객체를 if문에 넣는 가장 안전한 방법
struct Dummy
{
void true_function() {}
};
typedef void(Dummy::*F)();
operator F() { return fail() ? 0 : &Dummy::true_function; }
};
istream cin;
int main()
{
int n = 0 ; // 'a'
if (cin ){}
cin << n; // 1번 경우
// delete cin; // 2번 경우 문제, delete가 된다...
// void(*f)() = cin; // 3번 경우 문제
// void(istream::Dummy::*f)() = cin; // 4번 경우 문제, 하지만 일반 사용자는 Dummy를 알고 쓰기 어려움..
}
#include <iostream>
// using namespace std;
// C++11 에서는 변환 연산자에도 explicit를 사용 할 수 있다.
class istream // basic_istream
{
public :
bool fail() {return false;}
explicit operator bool() { return fail() ? false : true ;}
};
istream cin;
int main()
{
// bool b1 = cin ; // err
bool b1 = static_cast<bool>(cin) ; // ok
int n = 10;
// cin >> n ;
if (cin) {} // ok
// if (cin == false ) {} // error
}
#include <iostream>
// using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) : x(a), y(b) {}
};
class Point2
{
int x, y;
public:
explicit Point2(int a, int b) : x(a), y(b) {}
};
void foo(Point p) {};
void foo2(Point2 a) {};
int main()
{
foo({1, 1});
// foo2({1,1}) ; // error
Point p1(1 ,1);
Point p2{1, 1};
Point p3 = {1, 1};
Point2 ap1(1 ,1);
Point2 ap2{1, 1};
// Point2 ap3 = {1, 1}; // copy initialize error
}
728x90
반응형