C++选角问题
C++ casting issue
我尝试使用以下方法编译它(--std=c++0x):
- [FAIL with --std=c++0x flag] clang version 3.2-1~exp9ubuntu1 (tags/RELEASE_32/final) (基于 LLVM 3.2)
- [FAIL without --std=c++0x flag] clang version 3.2-1~exp9ubuntu1 (tags/RELEASE_32/final) (基于 LLVM 3.2)
- [FAIL without --std=c++11 flag] Apple LLVM version 5.0 (clang-500.2.79) (基于 LLVM3.3svn)
- [FAIL with --std=c++11 flag] Apple LLVM version 5.0 (clang-500.2.79) (基于 LLVM3.3svn)
- [PASS with --std=c++0x flag] gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)
- [FAIL without --std=c++0x flag] gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)
当它在 clang ubuntu 失败时,会产生以下错误:
test.cpp:26:37: error: no viable conversion from 'const P' to 'timeval'
return static_cast<timeval>(_p);
^~
/usr/include/x86_64-linux-gnu/bits/time.h:30:8: note: candidate constructor
(the implicit copy constructor) not viable: no known conversion from 'const P' to
'const timeval &' for 1st argument
struct timeval
^
/usr/include/x86_64-linux-gnu/bits/time.h:30:8: note: candidate constructor
(the implicit move constructor) not viable: no known conversion from 'const P' to 'timeval &&' for
1st argument
struct timeval
^
test.cpp:9:5: note: candidate function
operator const timeval() const {
^
test.cpp:13:5: note: candidate function
operator const int8_t() const {
^
我不确定我做错了什么。
#include <iostream>
#include <cstdint>
union P {
timeval _timeval;
int8_t _int8_t;
uint8_t _uint8_t;
operator const timeval() const {
return _timeval;
}
operator const int8_t() const {
return _int8_t;
}
};
struct Y {
operator const int8_t() const {
return static_cast<int8_t>(_p);
}
operator const timeval() const {
return static_cast<timeval>(_p);
}
P _p;
};
int main()
{
Y testobj;
timeval ret = static_cast<timeval>(testobj);
return 0;
}
作为起点,你错过了从#include
开始的#
。
#include <iostream>
#include <cstdint>
您也没有包含任何应定义类型 timeval
的标头。鉴于您显然正在使用的系统,您可能需要:
#include <sys/time.h>
如果您使用的是Windows,那可能是:
#include <winsock2.h>
可能还有更多的问题,但这至少应该让你开始朝着正确的大方向前进。
您可能需要
从转换运算符中删除第一个const
,因为您稍后尝试将联合转换为非常量值:
operator timeval() const {
return _timeval;
}
滥用转换运算符似乎是一个坏主意。如果要封装,请考虑创建适当的方法,例如 timeval getTimeval() const
。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题