I read the tutorial about class . The example code is
1 2 3 4 5 6 7 8 9 10
class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area () {return (width*height);}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
But then i get the error
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
I had to change it to the below to compile it.
My question is Why is that? in the example,the method CRectangle didn't specify a return type but it's correct but why did i get a error in my example?
and,in another example
1 2 3 4 5 6 7
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
I dont know what "CVector () {};" means...why is a "()" and a "{}"?
My question is Why is that? in the example,the method CRectangle didn't specify a return type but it's correct but why did i get a error in my example?
The CRectangle function is a constructor so it can't have a type. Your functions are not constructor so they have to have a return type.
CharChen wrote:
I dont know what "CVector () {};" means...why is a "()" and a "{}"?
This CVector is the default constructor function that take no arguments (hence the empty parentheses), and it's definition does nothing - hence the empty braces.
Having the definition of a function in the header file is called implicit inlining, and is done for functions that are trivial. Usually non-trivial functions are defined in the .cpp file.
Alright. The reason why it requires you to add bool to the Create function's return type is because Create is a function- all functions must have a return type specified. The example that you quoted shows three cases:
The first case is the default constructor if no arguments are given, such as if you were to just say "Cvector a". The () is the arguments given (none) and the {} is what it does (nothing). You see, the reason for that is because when you add a constructor to a class, the default constructor goes away, so you have to re-make it.
The second case is just a standard constructor.
The third case is overloading the operator +.
In classes, all functions must have a return type specified. The only ones that don't are constructors and destructors, which are only known because they don't have a return type specified.
CRectangle() is a constructor, a special method that is called on the initialization of a class object, and a return value is not specified for this function. Member functions such as Create(), must specify a return value.
For CVector, CVector() is the constructor for CVector. CVector() { } is the implementation of the constructor, which does nothing. It is valid code to put function definitions inside the class declaration; for example, all the CRectangle code could have been put inside class CRectangle {...};