Code:template <class T>
T operator++(T num)
{
cout<<"In overload function"<<endl;
return T result = num++;
}
int main()
{
int num=5;
int result = operator++(num); //whats the problem with this???
}
Why does this fail to compile?
Printable View
Code:template <class T>
T operator++(T num)
{
cout<<"In overload function"<<endl;
return T result = num++;
}
int main()
{
int num=5;
int result = operator++(num); //whats the problem with this???
}
Why does this fail to compile?
Because you're trying to declare a variable inside a return statement.
And by the way... I'd think for a minute before committing/submitting this... whatever it does.
The return statement is not the problem here.
I am visual studio 2008 if thats any help.
Oh, really?! Then you tell me why this fails to compile:
Code:int main()
{
return int i = 0;
}
No need to be smart, what i was saying was even when i change the return part around it still fails. The error i get is before it reaches the return part.
To make it clearer for you
Code:template <class T>
T operator++(T num)
{
cout<<"In overload function"<<endl;
T result = num++;
return result
}
int main()
{
int num=5;
int result = operator++(num); //whats the problem with this???
}
This still fails.
For one thing, you cannot overload operator++ for int.Quote:
Originally Posted by newbie30
Basically, it looks like you are trying to implement postfix operator++ in terms of prefix operator++, which is weird: the opposite is more normal. Nonetheless, if you want an example:
Personally, I feel that a more useful thing would be to define postfix operator++ in terms of prefix operator++, e.g.,Code:#include <iostream>
class X
{
public:
X(int num) : num(num) {}
int get() const
{
return num;
}
X operator++(int)
{
X temp(*this);
++num;
return temp;
}
private:
int num;
};
template <class T>
T& operator++(T& x)
{
x++;
return x;
}
int main()
{
X x(5);
X result = operator++(x);
std::cout << x.get() << ' ' << result.get() << std::endl;
}
Code:template<class T>
T operator++(T& x, int)
{
T temp(x);
++x;
return temp;
}
No, notice that postfix operator++ is used in the implementation of the function template prefix operator++. Incidentally, note that my example also corrects the function signature and return type.Quote:
Originally Posted by jefranki