2

このプログラムとそれが生成しているエラーを見てください:

#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]

問題を見つけるのを手伝ってもらえますか?ありがとうございました

4

2 に答える 2

6

あなたの「Bb2();」は、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;

詳細については、以下を参照してください。

于 2013-03-14T06:18:04.150 に答える
2
B b2();

これは関数宣言であり、変数宣言ではありません。

関数名はb2引数を取らず、型のオブジェクトを返しますB

C++で厄介な解析を検索します。

于 2013-03-14T06:17:37.717 に答える