代码之家  ›  专栏  ›  技术社区  ›  John

类中的C++方法定义是否必须指定返回类型?

  •  2
  • John  · 技术社区  · 14 年前

    刚刚看到 this question 关于C++类和程序中的分段错误问题。

    我的问题与阶级定义有关。在这里,正如它被张贴的那样:

    class A { 
        int x; 
        int y;
    
        public: 
        getSum1() const { 
            return getx() + y; 
        } 
    
        getSum2() const { 
            return y + getx(); 
        }
    
        getx() const { 
            return x; 
        }     
    } 
    

    到目前为止,关于这个问题的所有答案都没有提到方法的返回类型。我希望他们的定义是

    int getSum1() const { ....
    int getSum2() const { ....
    int getx() const { ....
    

    int 必须在那里吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   Richard Cook    14 年前

    是的, int 我们必须在那里。原始代码示例无效(正如其他人提到的,代码最初可能是C而不是C++)。首先,类声明需要一个终止分号,以便有机会编译。G+报告:

    foo.cpp:3: note: (perhaps a semicolon is missing after the definition of ‘A’)
    

    添加我们得到的分号:

    class A { 
      int x; 
      int y;
    
    public: 
      getSum1() const { 
        return getx() + y; 
      } 
    
      getSum2() const { 
        return y + getx(); 
      }
    
      getx() const { 
        return x; 
      }     
    };
    

    但还是失败了。G++将报告以下内容:

    foo.cpp:8: error: ISO C++ forbids declaration of ‘getSum1’ with no type
    foo.cpp:12: error: ISO C++ forbids declaration of ‘getSum2’ with no type
    foo.cpp:16: error: ISO C++ forbids declaration of ‘getx’ with no type
    
        2
  •  4
  •   JoeG    14 年前

    是的,在C++返回类型中 必须 具体说明。有关C和C++的比较,请参见 here .

        3
  •  1
  •   Vinzenz    14 年前

    是的,他们必须在那里。