簡體   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