Does a C++ method definition in a class have to specify the return type?
Just saw this question relating to a segmentation fault issue in a C++ class and program.
My question relates to the class definition. Here it is as it was posted:
class A {
int x;
int y;
public:
getSum1() const {
return getx() + y;
}
getSum2() const {
return y + getx();
}
getx() const {
开发者_运维知识库 return x;
}
}
None of the answers on that question so far made any mention about the return types of the methods. I'd expect them to be defined like
int getSum1() const { ....
int getSum2() const { ....
int getx() const { ....
Do the int
s have to be there?
Yes, in C++ return types must be specified. For a comparison between C and C++, see here.
Yes, the int
s have to be there. The original code sample is not valid (as someone else mentioned the code may have originally been C instead of C++). Firstly, the class declaration needs a terminating semicolon to stand a chance of compiling. g++ reports:
foo.cpp:3: note: (perhaps a semicolon is missing after the definition of ‘A’)
Adding the semicolon we get:
class A {
int x;
int y;
public:
getSum1() const {
return getx() + y;
}
getSum2() const {
return y + getx();
}
getx() const {
return x;
}
};
Which still fails. g++ will report the following:
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
Yes they do have to be there.
精彩评论