繁体   English   中英

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

[英]Does a C++ method definition in a class have to specify the return type?

刚刚看到这个问题与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必须在那里吗?

是的, 必须在C ++中指定返回类型。 有关C和C ++的比较,请参见此处

是的, 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

是的,他们必须在那里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM