c++ - 用户定义类型的隐式类型转换

标签 c++ types implicit user-defined

为什么下面的源码中自定义类型没有进行隐式类型转换?

到类型 A 的隐式类型转换应该发生在注释行上,但它没有发生,并且该行上发生了错误。

我想知道这个错误的语法规则和解决方案。

#include <iostream>

using namespace std;

class A {
   int v;
public:
    A(int _v): v(_v) {}
    operator int (void) const {
        return v;
    }
    friend ostream& operator << (ostream& os, const A& s) {
        return os << "A: " << s.v;
    }   
};

class B {
    int x, y;   
public:
    B(int _x, int _y): x(_x), y(_y) {}
    operator A(void) const {
        return A(x+y);
    }
};

int main(void)
{
    B b(1,2);
    cout << A(b) << endl;
    cout << (A)b << endl;
    cout << b << endl;     // error --> why?
    return 0;
}

-->附加问题

感谢 Sam Varshavchik 的回复。

如下定义A类可以解决这个问题。

class A {
   int v;
public:
    A(int _v): v(_v) {}
    operator int (void) const {
        return v;
    }
    friend ostream& operator << (ostream& os, const A& s);
};

ostream& operator << (ostream& os, const A& s){
    return os << "A: " << s.v;
}

//////////////

class A {
   int v;
public:
    A(int _v): v(_v) {}
    operator int (void) const {
        return v;
    }
    friend ostream& operator << (ostream& os, const A& s){
        return os << "A: " << s.v;
    }
};

ostream& operator << (ostream& os, const A& s);

是否将“operator <<”声明为好友在这里似乎并不重要。 由于该函数是全局函数,因此可以在其他类或其他函数中引用它。 我认为定义函数的 block 是在 A 类内部还是外部很重要。 为什么使用内部定义时需要声明函数?我想知道语法基础。

最佳答案

这一定与重载解析、友元函数、隐式转换之间的关系相关的神秘规则有关。因为这不仅仅是关于隐式转换。您还定义了一个重载 operator<<这是一个友元函数。

通过简单地去掉友元函数,以下代码在 gcc 9.2 上可以正常编译。它也不会伤害 get rid of using namespace std; , as well :

#include <iostream>

class A {
   int v;
public:
    A(int _v): v(_v) {}
    operator int (void) const {
        return v;
    }
};

std::ostream& operator << (std::ostream& os, const A& s) {
    return os << "A: " << (int)s;
}

class B {
    int x, y;
public:
    B(int _x, int _y): x(_x), y(_y) {}
    operator A(void) const {
        return A(x+y);
    }
};

int main(void)
{
    B b(1,2);
    std::cout << A(b) << std::endl;
    std::cout << (A)b << std::endl;
    std::cout << b << std::endl;     // No more error
    return 0;
}

关于c++ - 用户定义类型的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60695692/

相关文章:

c++ - 我如何告诉 cmake 在哪里输出它的构建数据?

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

scala - Scala 编译器会找出 CanBuildFrom 的哪个实例?

c++ - 划分快速排序逻辑错误

c++ - CLion 只显示调试器中的结果类型,而不是实际值

c++ - vector 类型值不匹配错误

haskell - `HFix` 如何在 Haskell 的 multirec 包中工作?

haskell - 通过解析字节流返回类型列表,其中长度直到运行时才知道

java - 我们会通过隐式转换来降低精度吗

plsql - 在 PL/SQL 中,隐式游标是否会无法关闭?