Sky89
unread,Jun 5, 2018, 8:01:58 PM6/5/18You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
Hello...
I think C++ is really powerful, read the following:
I have said before that C++ allows some "implicit" conversions
and that is not good, but i have learned more C++ and now i
am understanding it more, and i think C++ is really powerful !
because you can "control" implicit conversiosn(that means disallowing
implicit conversions) by doing the following in C++, look carefully at
the following C++ code that you can extend:
===
include <iostream>
#include <stdexcept>
struct controlled_int {
// allow creation from int
controlled_int(int x) : value_(x) { };
controlled_int& operator=(int x) { value_ = x; return *this; };
// disallow assignment from bool; you might want to use
BOOST_STATIC_ASSERT instead
controlled_int& operator=(bool b) { std::cout << "Exception: Invalid
assignment of bool to controlled_int" << std::endl;
throw; return *this; };
// creation from bool shouldn't happen silently
explicit controlled_int(bool b) : value_(b) { };
// conversion to int is allowed
operator int() { return value_; };
// conversion to bool errors out; you might want to use
BOOST_STATIC_ASSERT instead
operator bool() { std::cout << "Invalid conversion of controlled_int
to bool" << std::endl;
// throw std::logic_error("Exception: Invalid conversion of
controlled_int //to bool");
};
private:
int value_;
};
int main()
{
controlled_int a(42);
// This errors out:
// bool b = a;
// This gives an error as well:
a = true;
std::cout << "Size of controlled_int: " << sizeof(a) << std::endl;
std::cout << "Size of int: " << sizeof(int) << std::endl;
return 0;
}
===