C++ 编译器错误:“之前的声明符无效”

Deb*_*der 8 compiler-errors factory-method shared-ptr make-shared c++11

这是我的代码。编译时出现错误

\n\n
\n

\xe2\x80\x98geometry\xe2\x80\x99 之前的声明符无效

\n
\n\n

在第 16 行和第 48 行,我不确定我做错了什么。请指教。

\n\n
#include <iostream>\n#include <memory>\n#include <vector>\nusing namespace std;\nclass FactGeometry {   //Factory class\npublic:\n    static std::shared_ptr<FactGeometry>geometry( int choice );\n    virtual void calcArea() = 0;\n};\n\nclass CalcRectangle :public FactGeometry {\n    void calcArea() {\n        double ll, bb, Area;\n        std::cout << "\\nEnter the length = ";\n        std::cin >> ll;\n        std::cout << "\\nEnter the breadth = ";\n        std::cin >> bb;\n        Area = ll * bb;\n        std::cout << "\\nArea = " << Area;\n    }\n}; //end class\n\nclass CalcTraingle :public FactGeometry {\n    void calcArea() {\n        double bb, hh, Area;\n        std::cout << "\\nEnter the base = ";\n        std::cin >> bb;\n        std::cout << "\\nEnter the height = ";\n        std::cin >> hh;\n        Area = 0.5 * bb * hh;\n        std::cout << "\\nArea = " << Area;\n    }\n};\n\nFactGeometry std::shared_ptr<FactGeometry>geometry( int choice ) {\n    switch ( choice ) {\n    case 1: return shared_ptr<FactGeometry>( new CalcRectangle );\n        break;\n    case 2: return shared_ptr<FactGeometry>( new CalcTraingle );\n        break;\n    default: std::cout << "EXIT";\n        break;\n    }\n} //end class\n\nint main() {\n    cout << "Hello World";\n    int choice;\n    std::vector<std::shared_ptr<FactGeometry>> table;\n    while ( 1 ) {\n        std::cout << "1. Rectangle 2. Triangle";\n        std::cout << "Enter Choice :";\n        std::cin >> choice;\n        if ( ( choice != 1 ) || ( choice != 2 ) )\n            break;\n        else\n            table.push_back( FactGeometry::make_shared<FactGeometry>geometry( choice ) );\n    }\n    for ( int i = 0; i < table.size(); i++ ) {\n        table[i];\n    }\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我正在为工厂方法类编写代码,但在 \xe2\x80\x98geometry\xe2\x80\x99 之前收到此错误作为无效声明符。我不确定我做错了什么

\n

小智 31

对于在 C++ 中遇到 \xe2\x80\x9cinvalid declarator before\xe2\x80\x9d 类似问题的人,即使您编写的语法看起来不错,请检查上一行中的分号。

\n

  • 发现!它甚至可以是结构体的声明;),请注意这一点。 (4认同)