当显式转换是必需的并且隐式转换将不起作用时
when explicit conversion is necessary and implicit will not work
当我有 2 个具有实现转换构造函数和转换运算符的类时,是否有可能需要显式转换的情况,因为隐式不起作用?(我用 2 个类做例子,看看继承是否有任何区别)
当可以隐式应用多个转换时,为了解决歧义,可能需要显式转换:
#include <iostream>
using namespace std;
void f(double x) {
cout << "Doublen";
}
void f(int x) {
cout << "Integern";
}
struct C
{
C(float x) { this->x = x; }
operator int() { return (int)x; }
operator double() { return (double)x; }
float x;
};
int main(int argc, char* argv[])
{
C c(1);
f(c); // error C2668: 'f' : ambiguous call to overloaded function
f(static_cast<double>(c)); // calls f(double)
f(static_cast<int>(c)); // calls f(int)
}
下面是
一个继承示例,其中显式类型转换是必需的:
// Base class.
class Foo
{
};
// Derived class.
class Bar : public Foo
{
public:
void SomeMethod()
{
cout << "I a in Bar!" << endl;
}
};
// Global method; input argument is derived class pointer.
void method(Bar* obj)
{
obj->SomeMethod();
}
// main
int main()
{
Foo* obj1 = new Foo();
method(obj1); // This line will error when passing the base class object
// error C2664: 'method' :
//cannot convert parameter 1 from 'Foo *' to 'Bar *'
return 0;
}
所以这里你需要显式类型转换为派生类。
method((Bar*) obj1);
希望这有帮助。
只要你有相关的构造函数
class A
{
// ...
A(const B& b); // or similar
};
类型的隐式强制转换
B b(...); // B is the other class
A a = b;
或
B b(...);
A a(b);
会工作。
相关文章:
- 嘿,我正在尝试将此c ++转换为javascript,但有些东西不起作用
- C++实用程序::转换在静态链接库中不起作用
- 为什么转换不起作用
- 隐式用户定义的转换不起作用,因为在编译C 时无法识别运算符和转换构造函数
- pybind11:Python 到 C++ 数据类型转换不起作用
- sqlite3_exec()!= SQLITE3_OK. 尝试在 OOP 中转换不起作用
- 为什么这种从int到double的转换不起作用?
- C++数组,数组转换不起作用
- OpenCV c++HoughLines转换不起作用
- 不同模型的转换不起作用
- C++ 特殊字符的 Solaris 大写转换不起作用
- 在 C++ 中使用构造函数进行类型转换不起作用?
- C++隐式转换不起作用
- CUDA 和 OpenCV。从 Mat 到 GpuMat 的转换不起作用
- 隐式类型转换不起作用
- 为什么这个角色转换不起作用?
- 为什么从int到double的简单强制转换不起作用?
- 从 std::string 到类的隐式转换不起作用
- 现代OpenGL投影视图模型转换不起作用
- 为什么这种双精度到整型的转换不起作用?