Jump to content
  • Advertisement
Sign in to follow this  
wforl

implicit op*

This topic is 3713 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I dont really understand how the following code is working, regarding how the line
std::cout << (a * 8).val;

is being implicitly casted to
std::cout << (a * temp(8)).val;

i understand how doubles, floats and ints etc can be implicitly converted to one another, but i dont understand how the int object '8' is being casted as 'temp(8)'. Here is the whole code
#include <iostream>

class temp
{
public:
	temp(int in) : val(in){};
	const temp operator* (const temp& in) const
	{ 
		temp t(0); 
		t.val = (this->val * in.val);
		return t;
	};
	
	int val;
};

int main()
{
	temp a(9);
	std::cout << (a * 8).val;

	//pause
	getchar();
};



Also i have been told i can use explicit command on the op*() to stop the casting. But i havent had much luck, when using it as follows i get the error
Error	1	error C2071: 'temp::operator *' : illegal storage class	c:\users\admin\documents\visual studio 2008\projects\gggggg\gggggg\g.cpp	9


explicit const temp operator* (const temp& in) const
	{ 
		temp t(0); 
		t.val = (this->val * in.val);
		return t;
	};

Share this post


Link to post
Share on other sites
Advertisement
In your temp class there is a single argument constructor, that will cause an implicit cast from the argument type to the class. If you do not want this then declare the constructor explicit.


class temp
{
public:
explicit temp(int in) : val(in){};
const temp operator* (const temp& in) const
{
temp t(0);
t.val = (this-&gt;val * in.val);
return t;
};

int val;
};



EDIT: source tags :/

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!