Saturday, May 9, 2009

Can someone explain how to create an overloaded assignment operator in C++?

I need an overloaded assignment operator, and a copy constructor. Can't seem to figure it out. The .h file is pasted below.


//Hand.h


//header file


#ifndef HAND_H


#define HAND_H


#include "Card.h"





class Hand


{


public:


Hand();





//overloaded assignement opereator


Hand%26amp; Hand::operator=(Hand%26amp; c);





virtual ~Hand();





//copy constructor


Hand(Hand%26amp; c);





//adds a card to the hand


void Add(Card* pCard);





//clears hand of all cards


void Clear();





//gets hand total value, intelligently treats aces as 1 or 11


int GetTotal() const;





protected:


vector%26lt;Card*%26gt; m_Cards;


};


#endif


//Card.h


//Header File





#ifndef CARD_H


#define CARD_H





class Card


{


public:


enum rank {ACE = 1, TWO, ..};


enum suit {CLUBS, DIAMONDS, ..};





friend ostream%26amp; operator%26lt;%26lt;(ostream%26amp; os, const Card%26amp; aCard);





Card(rank r = ACE, suit s = SPADES, bool ifu = true);





//returns the value of a card, 1 - 11


int GetValue() const;


//flips a card


void Flip();


private:


rank m_Rank;


suit m_Suit;


bool m_IsFaceUp;


}

Can someone explain how to create an overloaded assignment operator in C++?
The purpose of both those methods is to create an instance of the class that is identical in behavior to an existing instance.





If you don't declare them yourselves, the compiler will do it for you if required and if it's possible for it to do so. So unless you have something specific to do in the copy, one normally let the compiler take care of generating them. The compiler will produce a version which simply copy each of the variable from one instance to the other.





If you do require to perform something different (which is normally the case if any of your members are pointers, you then redefine them.





Hand%26amp; Hand::operator=(const Hand%26amp; c);


Hand(const Hand%26amp; c);





Here your only member is a vector of card*. So both method would consist of inserting each card from the existing instance vector, and inserting them in the new instance vector. BUT you have to decide if the second instance will insert the exact same card in it's vector, or an identical copy of it. If you insert the same cards, they can't be deleted or modified by any of those hand without affecting the other and this is a big problem, and unless you have a card manager that is responsible for that this solution is very dangerous. So you're better to insert identical copy of the cards in the second vector. Which will require a copy constructor and assignment operator on the card too.. Or at least a clone method, which will allow you to create a copy of each card found in the first hand, and insert them into the second hand vector.





This being said, you will need a copy constructor and assignment operator for the class hand. But that class is quite simple, and the compiler will normally be able to produce them for you, since it only contains plain values.


Solve this problem with use of Ternary Operator in c language.?

write a c program which uses the ternary operator to print -1, 0 or 1 if the value input to it is negative, zero or positive.





ternary operator ----------------------------------------...


first_exp?second_exp : third_exp;





--------------------------------------...


if (first_exp)


x=second_exp;


else


x=third_exp;


--------------------------------------...


i think someone knowing this operator would solve it it seconds.





thanks in advance, i really need it.

Solve this problem with use of Ternary Operator in c language.?
Yes it can be solved using twoTernary operations in a row.





X%26gt;0? X=1:X


X%26lt;0? X=-1:X





If its not greater or less than zero it must be zero. No third test is needed for zero because you have eliminted all other possibilities which would change X if X is anything esle but zero
Reply:ternary operator is a substitute for if..else statement, meaning, there is only a TRUE part and a FALSE part...the problem cannot be solve by ternary alone..
Reply:(x%26lt;0)?(x= -1):((x%26gt;0)?(x=1:x=0)).This is the answer for your question. read it carefully u'll understand.





its simple its nested ternary operator.tat is if x%26lt;0 it sud b -Ve so x= -1 else it will execute the next expression which is another ternary operation tat is if x%26gt;0 it should be greater than 0 that is 1. else its 0. ok.so all 0,1,-1 will be printed accordingly..


How to implement sizeof operator in c lanaguage?

The sizeof operator is part of the standard library,but is it possible to


write a c program or function that does the job of sizeof?

How to implement sizeof operator in c lanaguage?
as the other person said, sizeof operator is evaluated at compile time, not run time.





basically, what it does is it looks at what you declared the size of a string to be, and returns that number.





example:


char str[100];


char message[] = "hello";


int size;





strcpy(str, message);


size = sizeof(str);


//size = 100;








if you want to know the actual size of the array then you can use strlen() function.


example:





char str[100];


char message[] = "hello";


int size;





strcpy(str, message);


size = strlen(str);


//size = 5;





can you write a function to dupe sizeof()?


im not sure why you would want to since sizeof() works for what it was intended to do. you could easily dupe the strlen() function though.





int strlen(char *str)


{


int length = 0;


while (*(str + length) != NULL)


{


length++;


}


return (length);


}
Reply:The sizeof operator is not part of the C standard library. It may look like a function call, but that is not what it really is. It is a unary operator of the C language itself, just like the unary minus operator. sizeof is evaluated by the compiler at compile-time, not at run-time.





It is technically possible to implement a function that has the same functionality as sizeof, but you would need to know a lot of intricate details about your compiler, and the function would need to have at least a slightly different syntax than the sizeof operator. For example the sizeof operator may operate on primitive data type identifers, like sizeof(int), but normal functions can't do this.


What does the <<= operator do? C Programming?

In c programming what does the %26lt;%26lt;= operator do?

What does the %26lt;%26lt;= operator do? C Programming?
Assignment by Bitwise Left Shift. It shifts all the bits in a value left by one and assigns it to a variable.

floral

How to recognise whitespaces in c++ by using '>>' operator. I kknow that'>>' will neglect spaces.

I am trying to read from a file which contains some code. My goal is to separate tokens and display them. I am writing code in c++.





For Example,





If input is:


void main()


{


int n;


}





Output should be





Keyword void


keyword main


separator (


separator )


separator {


keyword int


identifier n


separator ;


separator }








Now my problem is that


i am trying to read from the file using %26gt;%26gt; operator


i.e


char s;


ifstream infile;


infile%26gt;%26gt;s





This fragment of code reads the data from the file character by character. The %26gt;%26gt; operator in c++ will not consider whitespaces. So as soon as it completes reading 'void' it is neglecting whitespace and start reading 'main'. So it is taking 'voidmain' as a single string and giving output as





identifier voidmain





What should i do to check for whitespace between the 'void' and 'main'


so that i can get the correct out put





keyword void


keyword main





Can u please help me out





Regards,


Prudeesh C Makkapati,


Graduate Teaching Assistant,


Computer Science Dept.


University of Alabama in Huntsville

How to recognise whitespaces in c++ by using '%26gt;%26gt;' operator. I kknow that'%26gt;%26gt;' will neglect spaces.
You're probably reading in one character at a time.


Use strings (STL).





#include %26lt;string%26gt;





string s;


ifstream f;





"f %26gt;%26gt; s;" will read in one word at a time.
Reply:You could either use the functions


get() // returns the next character


get(c) // puts next character in c


getline(s, n, t) // gets n number of characters up until t, use t=' ' (space), puts result into string s. t is not included in s


get(s, n, t) // like getline except leaves t on the stream





Or, use the manipulator 'noskipws' do not skip whitespace.


infile %26gt;%26gt; noskipws; // after this is will skip whitespace


so you could use the line


infile %26gt;%26gt; s; // afterwards.





If you need to change it back, use


infile %26gt;%26gt; skipws;


How can the scope resolution operator in c++ be replaced by anything else?

in c++, while implementing inheritance, scope resolution operator i.e. '::' is used to specify the visibilty mode of derived class.is there any replacement for this operator?(maybe some other operator or something else).if yes,then wat is the replacement?

How can the scope resolution operator in c++ be replaced by anything else?
Scope resolution operator "::" cannot be overloaded because it is a base address resolution operator. in C++, while implementing inheritance, redefinition of function is possible instead of using scope resolution operator.
Reply:There is no replacement for a scope resolution operation. The member functions and variables can be accessed using a class objective pointer but a scope resolution is needed to specify the relation between function of a class with other functions and classes.
Reply:just by using an accessed member at the end of class definition
Reply:I dont think any other operator is there to replace scope resolution operator.


In worst case, if u really any alternative, then u can overload any operator so that it function same as ' :: '. But this is never recommed option.


Operator overloading in c++?

How do I overload the [] operator in c++? I have a card deck class where I want to access cards by deck[1], instead of deck.getCard(1).





Note: I have a private vector where I am storing the cards.

Operator overloading in c++?
int operator [] (int ndx)


{


// put anything you want here to accesss


// element "ndx". Just return the value


// of that element as the return value of


// this function.


return value_of_ndx_element_of_your_vector;


}
Reply:Lost me with vectors, but I do a web search for c++ tutorials and most allow you to search their sites for specific answers.


Help overloading assignment operator in C++?

Trying to overload the assignment operator in C++





Point%26amp; Point::operator=(const Point%26amp; p)


{


if(this != %26amp;p)


{


delete [] label; //Deletes label


label = new char(strlen (*(p.label)));


strcpy(label, (*(p.label)));


x = (*(p.x)); //Copies x.


y = (*(p.y)); //Copies y


}


return *this; //Returns *this.


}





h:\point\point\point\point.cpp(64) : error C2664: 'strlen' : cannot convert parameter 1 from 'char' to 'const char *'


Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast


h:\point\point\point\point.cpp(64) : fatal error C1903: unable to recover from previous error(s); stopping compilation





With line 64 commented out:





h:\point\point\point\point.cpp(65) : error C2664: 'strcpy' : cannot convert parameter 2 from 'char' to 'const char *'


Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast


h:\point\point\point\point.cpp(66) : error C2440: '=' : cannot convert from 'double' to 'double *'


h:\point\point\point\point.cpp(67) : error C2440: '=' : cannot convert from 'double' to 'double *'

Help overloading assignment operator in C++?
label = new char(strlen (*(p.label)));


strcpy(label, (*(p.label)));


x = (*(p.x)); //Copies x.


y = (*(p.y)); //Copies y





The code above replace with





label = new char(strlen ((p.label)));


strcpy(label, ((p.label)));


x = p.x; //Copies x.


y = p.y; //Copies y
Reply:????
Reply:Ok, The line


Point%26amp; Point::operator = (const Point%26amp; p)


This means that your argument to the function is passed by reference, and returns a reference.


A reference argument is used like a regular argument, no special treatment required.


I believe the assignment operator is redefined as


Point%26amp; Point::operator = (const Point%26amp; p)


The complete function would be


Point%26amp; Point::operator = (const Point%26amp; p)


{


if (this == %26amp;p)


return *this;


char *temp;


double dx, dy;


temp = new char[strlen(p.label) + 1];


strcpy(temp, p.label);


dx = p.x;


dy = p.y;


x = dx;


y = dy;


delete label;


label = new char[strlen(temp) + 1];


strcpy(label, temp);


delete temp;


return *this;


}

daisy

&& operator in C# ??? can help me plsss...?

protected void btnsearch_Click(object sender, EventArgs e)


{


if (DateTime.Parse(Date1.Text) %26lt; DateTime.Now.Date)


{


lblErrSearch.Visible = true;


lblErrSearch.Text = "The date cannot be eariler than today";


}


else


{


lblErrSearch.Text = "Hello World";


}


}





Can help me to do Validation in C#?


Actually I have 2 textbox for Date (Date1 and Date2). There is a popup calender will appear below each texbox . I want to validate :


%26gt; when the date chosen is ealier than today's date.


%26gt;the code above is for one Date1 textbox - and its working perfectly! but I want the same error message to be displayed when the Date2 is earlier than today's date.


%26gt; I want to check both textbox.





I am not sure how to use the AND OPERATOR in c#


I tried this code(modify the IF..THEN ELSE )..but it doesn't work =(





if (DateTime.Parse(Date1.Text) %26amp;%26amp; DateTime.Parse(Date2.Text)%26lt; DateTime.Now.Date)





i donno whtr to use %26amp;%26amp; or %26amp;

%26amp;%26amp; operator in C# ??? can help me plsss...?
Well, for your expression, you really want an || statement (or operator) - that is, if date1 %26lt; now OR date2 %26lt; now, throw an error. If you use an and (well, if you use it correctly anyways), the condition would only be true when both are true, only capturing a subset of your error cases.


----


if ( (DateTime.Parse( Date1.Text ) %26lt; DateTime.Now.Date) ||


( DateTime.Parse( Date2.Text ) %26lt; DateTime.Now.Date) )


---


Good practice for a conditional this long is to represent the terms with accurately named boolean variables, which would make this whole thing more readable:





bDate1Bad = DateTime.Parse ( Date1.Text ) %26lt; DateTime. Now. Date;





bDate2Bad = DateTime.Parse ( Date2.Text ) %26lt; DateTime. Now. Date;





if ( bDate1Bad || bDate2Bad ) ...
Reply:The difference betwen the '%26amp;' operator and the '%26amp;%26amp;' operator is that when using the single %26amp;, the program will look at the first statement, and if it is false, it will not bother evaluating the second one. When you use the %26amp;%26amp; operator, both sides of the expression are evaluated, even if the first one is false. To be honest, I have never really coded a program where it mattered how the statment was interpreted, so I always use '%26amp;%26amp;' to be safe.


Now, about your issue... if the code snippet above is a direct copy, you have a logic problem : the first statement within the if is merely looking to see if Date.Text exists - you are not actually comparing it to anything. I am thinking you really want





If(DateTime.Parse(Date1.Text) %26gt; DateTime.Parse(Date2.Text)) %26amp;%26amp; ....





First, compare the first date to the second, and then see if either of the dates is earlier than today. In that case, you will need to add another comparison. FYI - I'm sure you have found this out already, but date/time objects are notoriously difficult to work with. To help prevent errors, I never let a user enter a date - I create combo boxes that force then to choose valid choices. That way I can control the input, and don't have to worry about invalid characters. You still need to check to make sure that the dates are not one before the other, but it makes the rest of the process much easier. Good luck.


Few exmples of operator overloading in c++?

i want to know about the syntex of overloding the operators


in c++ these operators are ++,+,=,%26lt;,%26gt;

Few exmples of operator overloading in c++?
check this link out: http://publib.boulder.ibm.com/infocenter...
Reply:there are comprehensive references in the net,just google it


C++ "=" operator overloading?

I have following class, I want to overload “=” operator, I did as following but I cant get success, any one can help me please


class String


{


private:


char * name;


public:


const char * getName() const { }


void setName(const char * aname) { }


friend char * operator=(char %26amp; str, const String %26amp;rhs );


}





char * operator= (char %26amp;str, const String %26amp;rhs )


{


str = const_cast%26lt;char * %26gt;(rhs.getName())


return *str;


}





Void main()


{


String obj;


Obj.setName(“Hello World “);


Char * myString = Obj;


Cout%26lt;%26lt;myString;


}

C++ "=" operator overloading?
Sure.





Your problem here is that the parameters for your operator = are (char %26amp;, String %26amp;). You have two problems here.





First, you want to make that char *%26amp;, not char %26amp;. As defined here, you have an operator = that copies a string into a single character.





The second problem is a little bigger. You are copying a pointer here instead of doing any sort of copying of contents. When done, myString wand Obj will point at the SAME string.





While this makes for a very fast copy, you're almost guaranteed to have problems later:





1. Notice what happens to myString when Obj is deleted. myString is now pointing at deleted memory. The reverse is true as well.





2. If myString changes, so does Obj. The reverse is true as well.





3. There is no safe way to destroy the name * in your string object because you don't know how many copies were made, and if those are still in use. I'm assuming here that the implementation of setName() will allocate new memory for name, and that your full version has a destructor.





I hope this helps. Good luck.
Reply:You have completely mixed your metaphors here.





First off, your operator = only needs to take one parameter, not two -- and that parameter is whatever type you want to be able to assign TO your String.





Second, your operator = should return a String%26amp;.





Third, in order to assign a String object to a char*, you need to overload the char* cast operator.





And finally, make sure you understand that char* is just a pointer -- to actually put anything IN your string, you're going to have to dynamically allocate memory.


C++ operator overloading?

You can overload the common arithmetic operators like +,-,* to perform different operations with the objects of the class.... but is it possible to overload the power or exponential operator '^' as well using the usual operator overloading procedure?

C++ operator overloading?
You can overload ^ but there is one important thing you need to remember. Normally ^ is the bitwise xor operator and it has a lower precedence than the arithmatic operators and you cannot change precedence by overloading. So





a ^ b - c;





is not going to do what you expect unless you use parenthesis, namely





(a ^ b) - c;
Reply:Yes, but you need to override the math library. You can write your own library that calls the math library for the basic and then overload it.

gladiolus

Help with C++! operator variables!?

I am making a c++ calculator and so far i can not go farther than addition


ex.


#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


long int a, b, result;


cout%26lt;%26lt;"Enter a number: ";


cin%26gt;%26gt; a;


cout%26lt;%26lt;"Enter another number: ";


cin%26gt;%26gt; b;


result = a + b;


cout%26lt;%26lt;"The sum is: ";


cout%26lt;%26lt; result;


cout%26lt;%26lt;"\n";


system("pause");


}


so how do i make a variable for operators such as +,-,*,/,%?

Help with C++! operator variables!?
Here is the source:





#include %26lt;iostream%26gt;


using namespace std;





double calc(double a, double b, int operation);





int main() {


double num1, num2, calcAnswer;


int operation;





cout %26lt;%26lt; "Enter operation, \n 1. Multiply \n 2. Divide \n 3. Add \n 4. Minus \n Enter Operation: ";


cin %26gt;%26gt; operation;


cout %26lt;%26lt; "Enter first number: ";


cin %26gt;%26gt; num1;


cout %26lt;%26lt; "Enter second number: ";


cin %26gt;%26gt; num2;





if (operation == 1 || operation == 2 || operation == 3 || operation == 4) {





calcAnswer = calc(num1, num2, operation);





cout %26lt;%26lt; "\n Answer: " %26lt;%26lt; calcAnswer;


cin.ignore();





} else {





cout %26lt;%26lt; "\n\n Invalid operation! \n";


cin.ignore();


}





return 0;


}





double calc(double a, double b, int operation) {





double answer;





if (operation == 1) {





answer = a * b;





} else if(operation == 2) {





answer = a / b;





}else if(operation == 3) {





answer = a + b;





}else if(operation == 4) {





answer = a - b;





}





return (answer);


}





Hope that helps. Sorry I did not have time to comment the code.
Reply:You can email me by going to my profile and click email cayson. Anyways, it is caysonhiivala@hotmail.com. I also emailed this to your yahoo! email. I am glad to help you at any time. I also have some good tips and freebies you can have if you want them, email me. Report It

Reply:Other operators should work just fine, example:





int1 * int2





Try including cstdlib ; see if that makes a difference


To understand the meaning and differences between A,B & C operator.?

I used to see in the job application website and noted that in the oil/gas industries, at most time they are looking for different level of production operators. It stated as A Operator, B operator or C operator. I don't know what exactly it means being an oil/gas production operator like me. I would be much appreciated if any one can detail out what it means?


Thanks.

To understand the meaning and differences between A,B %26amp; C operator.?
I've worked in manufacturing (not oil/gas) for 13 years and never heard of A, B and C operator as a skill-level sort of description. The only reference that popped into mind was A shift, B shift, and C shift...meaning it isn't skill level but what hours of the day/days of the week you work.





If it is describing skill level, it must be specific to the company/industry.


C++ operator overloading question?

Why would:


vectorClass nv = vectors[0] + vectors[1];


cout %26lt;%26lt; vectors[0] %26lt;%26lt; " + " %26lt;%26lt; vectors[1] %26lt;%26lt; " = " %26lt;%26lt; nv %26lt;%26lt; endl;





work, While:





cout %26lt;%26lt; vectors[0] %26lt;%26lt; " + " %26lt;%26lt; vectors[1] %26lt;%26lt; " = " %26lt;%26lt; vectors[0] + vectors[1] %26lt;%26lt; endl;





would not.





Here is some implementation:





vectorClass operator + ( const vectorClass %26amp;left, const vectorClass %26amp;right )


{


int a, b, c;


a = left.x + right.x;


b = left.y + right.y;


c = left.z + right.z;





return vectorClass( a, b, c );





}





ostream %26amp; operator %26lt;%26lt; ( ostream %26amp;out, vectorClass %26amp;right )


{





out %26lt;%26lt; "[" %26lt;%26lt; right.x %26lt;%26lt; ", " %26lt;%26lt; right.y %26lt;%26lt; ", " %26lt;%26lt; right.z %26lt;%26lt; "]";





return out;


}

C++ operator overloading question?
add another overloaded function like this


vectorClass operator + (const vectorClass %26amp;right )


{


int a, b, c;


a = x + right.x;


b = y + right.y;


c = z + right.z;





return vectorClass( a, b, c );





}
Reply:Could it be the simple allocation of the class?


Not a ++ major, but even my old school, we had to allocate the memory....which is what vectorClass nv =





does.