我想为这个容器分配一个size_t:
std::vector <nts::Tristate *> _components;
Run Code Online (Sandbox Code Playgroud)
要做到这一点,我想投const size_t &给nts::Tristate *
this->_components[0] = static_cast<nts::Tristate *>(&value);
Run Code Online (Sandbox Code Playgroud)
但是我有以下错误:
error: invalid static_cast from type ‘const size_t* {aka const long unsigned int*}’ to type ‘nts::Tristate*’
this->_components[0] = static_cast<nts::Tristate *>(&value);
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?
没有问你为什么要这样做,问题是这两种类型(size_t*和nts::Tristate*)是完全不相关的,你需要将一种类型重新交换为另一种类型.你做的事情reinterpret_cast.
应该注意的是,做这样的事情很可能会导致其他问题,这些问题将导致不确定的行为.你需要注意的一件事是if value是一个局部变量,因为那时你存储一个指向这个局部变量的指针,它将超出范围并消失.另一个是使用的程序的其余部分_components[0]需要知道它实际上不是指向nts::Tristate对象的指针而是指向size_t值的指针.简而言之,你所做的是非常危险的.