繁体   English   中英

用户定义的转换无效

[英]invalid user-defined conversion

请看一下这个程序及其产生的错误:

#include <iostream>
using namespace std;
    class A
    {
    public:

        virtual void f(){}
        int i;
    };

    class B : public A
    {
    public:
        B(int i_){i = i_;} //needed
        B(){}              //needed
        void f(){}
    };

    int main()
    {

        //these two lines are fixed(needed)
        B b;
        A & a = b;

        //Assignment 1 works
        B b1(2);
        b = b1;

        //But Assignment 2  doesn't works
        B b2();
        b = b2; // <-- error
    }

编译后,出现以下错误:

$ g++ inher2.cpp 
inher2.cpp: In function ‘int main()’:
inher2.cpp:32:10: error: invalid user-defined conversion from ‘B()’ to ‘const B&’ [-fpermissive]
inher2.cpp:14:6: note: candidate is: B::B(int) <near match>
inher2.cpp:14:6: note:   no known conversion for argument 1 from ‘B()’ to ‘int’
inher2.cpp:32:10: error: invalid conversion from ‘B (*)()’ to ‘int’ [-fpermissive]
inher2.cpp:14:6: error:   initializing argument 1 of ‘B::B(int)’ [-fpermissive]

你能帮我找到问题吗? 谢谢

你的“B b2();” 是C ++的“ 烦恼的解析 ”问题( 参见这里 - “ 最令人烦恼的解析 ”进一步采用了模糊的语法)。

它向C ++编译器查看您正在声明一个函数(预先声明)。

看看这个:

int foo(); //A function named 'foo' that takes zero parameters and returns an int.

B b2(); //A function named 'b2' that takes zero parameters and returns a 'B'.

当你以后做:

b = b2;

看起来您正在尝试将函数( b2 )分配给变量( b )。 要调用一个零参数的构造函数,请在没有括号的情况下调用它,你会没事的:

B b2;

有关更多信息,请参阅:

B b2();

它是一个函数声明, 而不是变量声明!

函数名是b2 ,它不带参数,返回B类型的对象。

在C ++中搜索令人讨厌的解析

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM