我明白这reinterpret_cast很危险,我只是这样做来测试它.我有以下代码:
int x = 0;
double y = reinterpret_cast<double>(x);
Run Code Online (Sandbox Code Playgroud)
当我尝试编译程序时,它给我一个错误说
从'float'类型转换为'double'类型无效
这是怎么回事?我认为reinterpret_cast是你可以用来将苹果转换为潜艇的流氓演员,为什么这个简单的演员不会编译?
我对c ++ 20功能之一(指定的初始化程序)有疑问(有关此功能的更多信息,请点击此处)
#include <iostream>
constexpr unsigned DEFAULT_SALARY {10000};
struct Person
{
std::string name{};
std::string surname{};
unsigned age{};
};
struct Employee : Person
{
unsigned salary{DEFAULT_SALARY};
};
int main()
{
std::cout << std::boolalpha << std::is_aggregate_v<Person> << '\n'; // true is printed
std::cout << std::boolalpha << std::is_aggregate_v<Employee> << '\n'; // true is printed
Person p{.name{"John"}, .surname{"Wick"}, .age{40}}; // it's ok
Employee e1{.name{"John"}, .surname{"Wick"}, .age{40}, .salary{50000}}; // doesn't compile, WHY ?
// For e2 compiler prints a warning "missing initializer …Run Code Online (Sandbox Code Playgroud) 有没有办法获得一个类的字段数?
struct Base {
char a;
int b;
};
struct Derived : Base {
std::string c;
};
static_assert(num_fields<Base>::value == 2);
static_assert(num_fields<Derived>::value == 1);
Run Code Online (Sandbox Code Playgroud)
我发现了这个问题,但它已经过时了 - 我希望可以用C++ 14/17拼接一些东西(毕竟我们现在有类似magic_get的东西- 可能是它的一些子集......?)
编辑: - 编译器钩子也可以工作,即使它只适用于MSVC或GCC或Clang - 我使用全部3.
我正在为结构使用初始值设定项列表。但是,它不适用于继承。
这段代码很好。
struct K {
int x, y;
};
K k {1, 2};
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误。
struct L : public K {};
L l {1, 2};
Run Code Online (Sandbox Code Playgroud)
此外,这不起作用。
struct X {
int x;
};
struct Y : public X {
int y;
};
Y y {1, 2};
Run Code Online (Sandbox Code Playgroud)
有没有办法使用具有继承结构的初始化列表。我在模板中使用它们,因此无论它是否是继承类,它都不会编译。
c++ ×4
aggregate ×1
c++11 ×1
c++20 ×1
casting ×1
inheritance ×1
struct ×1
templates ×1
type-traits ×1