4

クラス B をコンストラクターのパラメーターとして受け入れるクラス A があります。クラス B は int 値から構築できます。私の元のコードは非常に複雑ですが、非常に基本的なケースに縮小できたことを願っています。

class B {
public:
    explicit B(int a) : val(a) {}
private:
    int val;
};

class A {
public:
    A(const B & val) : value(val) {};
    void print() {
        //does nothing
    }

private:
    B value;
};


int main() {
    int someTimeVar = 22;
    A a(B(someTimeVar));
    a.print();
}

そして、これは私が得ているエラーコードです:

$ g++ test.cpp -Wall -O0
test.cpp: In function ‘int main()’:
test.cpp:22:7: error: request for member ‘print’ in ‘a’, which is of non-class type ‘A(B)’
     a.print();
       ^
test.cpp:20:9: warning: unused variable ‘someTimeVar’ [-Wunused-variable]
     int someTimeVar = 22;
         ^

GCC (4.9.2 20150304 (プレリリース))、プラットフォーム: arch Linux を使用しています。

main 関数に対する次の変更は、正常にコンパイルされます。

int main() {
    A a(B(22));
    a.print();
}

A a(); を使用していることはよく知っています。オブジェクトではなく、関数を宣言します。しかし、私は A a(B(some_val)) が同じことをするとは思っていませんでした。私の意見では、これがここで起こっていることです。

なぜこれが起こっているのか考えがありますか?


編集:すべての回答に感謝します。最も厄介な解析のアイデアについてさらに調査する必要があるようです。

ところで、clang を使用してコードをコンパイルすると、より有用なエラー メッセージと解決策が得られることがわかりました。

$ clang test.cpp 
test.cpp:21:8: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
    A a(B(someTimeVar));
       ^~~~~~~~~~~~~~~~
test.cpp:21:9: note: add a pair of parentheses to declare a variable
    A a(B(someTimeVar));
        ^
        (             )
test.cpp:22:6: error: member reference base type 'A (B)' is not a structure or union
    a.print();
    ~^~~~~~
1 warning and 1 error generated.
4

3 に答える 3