Search Results

Search found 4206 results on 169 pages for 'equals operator'.

Page 5/169 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Ternary operator in if-statement?

    - by Pindatjuh
    I've written the following if-statement in Java: if(methodName.equals("set" + this.name) || isBoolean() ? methodName.equals("is" + this.name) : methodName.equals("get" + this.name)) { ... } Is this a good practice to write such expressions in if, to separate state from condition? And can this expression be simplified?

    Read the article

  • Must parameter of assignment operator be reference?

    - by Tim
    When overloading assignment operator of a class in C++, must its parameter be reference? For example, class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } Can it be class MyClass { public: ... MyClass & operator=(const MyClass rhs); ... } ? Thanks!

    Read the article

  • Operator overloading in C++

    - by user265260
    If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?

    Read the article

  • Who deletes the copied instance in + operator ? (c++)

    - by Dima
    Hello, I searched how to implement + operator properly all over the internet and all the results i found do the following steps : const MyClass MyClass::operator+(const MyClass &other) const { MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this); result += other; // Use += to add other to the copy. return result; // All done! } I have few questions about this "process" : Isn't that stupid to implement + operator this way, it calls the assignment operator(which copies the class) in the first line and then the copy constructor in the return (which also copies the class , due to the fact that the return is by value, so it destroys the first copy and creates a new one.. which is frankly not really smart ... ) When i write a=b+c, the b+c part creates a new copy of the class, then the 'a=' part copies the copy to himself. who deletes the copy that b+c created ? Is there a better way to implement + operator without coping the class twice, and also without any memory issues ? thanks in advance

    Read the article

  • Why friend function is preferred to member function for operator<<

    - by skydoor
    When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ? class A { public: void operator<<(ostream& i) { i<<"Member function";} friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;} }; int main () { A a; A b; A c; cout<<a<<b<<c<<endl; a<<cout; return 0; } One point is that friend function enable us to use it like this cout<<a<<b<<c What other reasons?

    Read the article

  • operator overloading c++

    - by segfault
    When overloading operators, is it necessary to overload = <= and !=? It seems like it would be smart for c++ to call !operator= for !=, ! for operator<= and !< for operator=. Is that the case, or is it necessary to overload every function?

    Read the article

  • Problems with first argument being string when overloading the + operator in C++

    - by Chris_45
    I have an selfmade Stringclass: //String.h String & operator = (const String &); String & operator = (char*); const String operator+ (String& s); const String operator+ (char* sA); . . //in main: String s1("hi"); String s2("hello"); str2 = str1 + "ok";//this is ok to do str2 = "ok" + str1;//but not this way //Shouldn't it automatically detect that one argument is a string and in both cases?

    Read the article

  • Java: omitting a data member from the equals method.

    - by cchampion
    public class GamePiece { public GamePiece(char cLetter, int nPointValue) { m_cLetter=cLetter; m_nPointValue=nPointValue; m_nTurnPlaced=0; //has not been placed on game board yet. } public char GetLetter() {return m_cLetter;} public int GetPointValue() {return m_nPointValue;} public int GetTurnPlaced() {return m_nTurnPlaced;} public void SetTurnPlaced(int nTurnPlaced) { m_nTurnPlaced=nTurnPlaced; } @Override public boolean equals(Object obj) { /*NOTE to keep this shorter I omitted some of the null checking and instanceof stuff. */ GamePiece other = (GamePiece) obj; //not case sensitive, and I don`t think we want it to be here. if(m_cLetter != other.m_cLetter) { return false; } if(m_nPointValue != other.m_nPointValue) { return false; } /* NOTICE! m_nPointValue purposely omitted. It does not affect hashcode or equals */ return true; } @Override public int hashCode() { /* NOTICE! m_nPointValue purposely omitted. It should not affect hashcode or equals */ final int prime = 41; return prime * (prime + m_nPointValue + m_cLetter); } private char m_cLetter; private int m_nPointValue; private int m_nTurnPlaced;//turn which the game piece was placed on the game board. Does not affect equals or has code! } Consider the given piece of code. This object has been immutable until the introduction of the m_nTurnPlaced member (which can be modified by the SetTurnPlaced method, so now GamePiece becomes mutable). GamePiece is used in an ArrayList, I call contains and remove methods which both rely on the equals method to be implemented. My question is this, is it ok or common practice in Java for some members to not affect equals and hashcode? How will this affect its use in my ArrayList? What type of java Collections would it NOT be safe to use this object now that it is mutable? I've been told that you're not supposed to override equals on mutable objects because it causes some collections to behave "strangely" (I read that somewhere in the java documentation).

    Read the article

  • overloaded stream insertion operator with a vector

    - by Julz
    hi, i'm trying to write an overloaded stream insertion operator for a class who's only member is a vector. i dont really know what i'm doing. (lets make that clear) it's a vector of "Points" which is a struct containing two doubles. i figure what i want is to insert user input (a bunch of doubles) into a stream that i then send to a modifier method? i keep working off other stream insertion examples such as... std::ostream& operator<< (std::ostream& o, Fred const& fred) { return o << fred.i_; } but when i try a similar..... istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr.vertices; return inStream; } i get an error "no match for operator etc etc. if i leave off the .vertices it compiles but i figure it's not right? (vertices is the name of my vector ) and even if it is right, i dont actually know what syntax to use in my driver to use it? also not %100 on what my modifier method needs to look like. here's my Polygon class //header #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); public: //Constructor Polygon(const Point &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return (int) vertices.capacity();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; #endif //Body using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const Point &theVerts) { vertices.push_back (theVerts); } //Copy Constructor Polygon::Polygon(const Polygon &polyCopy) { vertices = polyCopy.vertices; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } any help greatly appreciated, sorry to be so vague, a lecturer has just kind of given us a brief example of stream insertion then left us on our own thanks. oh i realise there are probably many other problems that need fixing

    Read the article

  • overloaded stream insetion operator with a vector

    - by julz666
    hi, i'm trying to write an overloaded stream insertion operator for a class who's only member is a vector. i dont really know what i'm doing. (lets make that clear) it's a vector of "Points" which is a struct containing two doubles. i figure what i want is to insert user input (a bunch of doubles) into a stream that i then send to a modifier method? i keep working off other stream insertion examples such as... std::ostream& operator<< (std::ostream& o, Fred const& fred) { return o << fred.i_; } but when i try a similar..... istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr.vertices; return inStream; } i get an error "no match for operator etc etc. if i leave off the .vertices it compiles but i figure it's not right? (vertices is the name of my vector ) and even if it is right, i dont actually know what syntax to use in my driver to use it? also not %100 on what my modifier method needs to look like. here's my Polygon class //header #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); public: //Constructor Polygon(const Point &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return (int) vertices.capacity();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; #endif //Body using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const Point &theVerts) { vertices.push_back (theVerts); } //Copy Constructor Polygon::Polygon(const Polygon &polyCopy) { vertices = polyCopy.vertices; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } any help greatly appreciated, sorry to be so vague, a lecturer has just kind of given us a brief example of stream insertion then left us on our own thanks. oh i realise there are probably many other problems that need fixing

    Read the article

  • C++ Beginner - 'friend' functions and << operator overloading: What is the proper way to overload an

    - by Francisco P.
    Hello, everyone! In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is returned. Here's what I tried to do: ostream & Score::operator<< (ostream & os, Score right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } Here are the errors returned: 1>c:\users\francisco\documents\feup\1a2s\prog\projecto3\projecto3\score.h(30) : error C2804: binary 'operator <<' has too many parameters (This error appears 4 times, actually) I managed to get it working by declaring the overload as a friend function: friend ostream & operator<< (ostream & os, Score right); And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member). Why does this work, yet the code describe above doesn't? Thanks for your time! Below is the full score.h /////////////////////////////////////////////////////////// // Score.h // Implementation of the Class Score // Created on: 10-Mai-2010 11:43:56 // Original author: Francisco /////////////////////////////////////////////////////////// #ifndef SCORE_H_ #define SCORE_H_ #include <string> #include <iostream> #include <iostream> using std::string; using std::ostream; class Score { public: Score(string name); Score(); virtual ~Score(); void addPoints(int n); string scoreGetName() const; int getPoints() const; void scoreSetName(string name); bool operator>(const Score right) const; ostream & operator<< (ostream & os, Score right); private: string _name; int _points; }; #endif

    Read the article

  • Lua Operator Overloading

    - by Pessimist
    I've found some places on the web saying that operators in Lua are overloadable but I can't seem to find any example. Can someone provide an example of, say, overloading the + operator to work like the .. operator works for string concatenation? EDIT 1: to Alexander Gladysh and RBerteig: If operator overloading only works when both operands are the same type and changing this behavior wouldn't be easy, then how come the following code works? (I don't mean any offense, I just started learning this language): printf = function(fmt, ...) io.write(string.format(fmt, ...)) end Set = {} Set.mt = {} -- metatable for sets function Set.new (t) local set = {} setmetatable(set, Set.mt) for _, l in ipairs(t) do set[l] = true end return set end function Set.union (a,b) -- THIS IS THE PART THAT MANAGES OPERATOR OVERLOADING WITH OPERANDS OF DIFFERENT TYPES -- if user built new set using: new_set = some_set + some_number if type(a) == "table" and type(b) == "number" then print("building set...") local mixedset = Set.new{} for k in pairs(a) do mixedset[k] = true end mixedset[b] = true return mixedset -- elseif user built new set using: new_set = some_number + some_set elseif type(b) == "table" and type(a) == "number" then print("building set...") local mixedset = Set.new{} for k in pairs(b) do mixedset[k] = true end mixedset[a] = true return mixedset end if getmetatable(a) ~= Set.mt or getmetatable(b) ~= Set.mt then error("attempt to 'add' a set with a non-set value that is also not a number", 2) end local res = Set.new{} for k in pairs(a) do res[k] = true end for k in pairs(b) do res[k] = true end return res end function Set.tostring (set) local s = "{" local sep = "" for e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}" end function Set.print (s) print(Set.tostring(s)) end s1 = Set.new{10, 20, 30, 50} s2 = Set.new{30, 1} Set.mt.__add = Set.union -- now try to make a new set by unioning a set plus a number: s3 = s1 + 8 Set.print(s3) --> {1, 10, 20, 30, 50}

    Read the article

  • How to change the meaning of pointer access operator

    - by kumar_m_kiran
    Hi All, This may be very obvious question, pardon me if so. I have below code snippet out of my project, #include <stdio.h> class X { public: int i; X() : i(0) {}; }; int main(int argc,char *arv[]) { X *ptr = new X[10]; unsigned index = 5; cout<<ptr[index].i<<endl; return 0; } Question Can I change the meaning of the ptr[index] ? Because I need to return the value of ptr[a[index]] where a is an array for subindexing. I do not want to modify existing source code. Any new function added which can change the behavior is needed. Since the access to index operator is in too many places (536 to be precise) in my code, and has complex formulas inside the index subscript operator, I am not inclined to change the code in many locations. PS : 1. I tried operator overload and came to conclusion that it is not possible. 2. Also p[i] will be transformed into *(p+i). I cannot redefine the basic operator '+'. So just want to reconfirm my understanding and if there are any possible short-cuts to achieve. Else I need fix it by royal method of changing every line of code :) .

    Read the article

  • How to define a static operator<<?

    - by Pietro M
    Is it possible to define a static insertion operator which operates on the static members of a class only? Something like: class MyClass { public: static std::string msg; static MyClass& operator<< (const std::string& token) { msg.append(token); return *this; // error, static } }; alternatively: static MyClass& operator<< (MyClass&, const std::string &token) { MyClass::msg.append(token); return ?; } This is how I would like to use it: MyClass << "message1" << "message2"; Thank you!

    Read the article

  • Operator Overloading with C# Extension Methods

    - by Blinky
    I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class. Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text"); Here's the syntax for creating an extension method for StringBuilder: public static class sbExtensions { public static StringBuilder blah(this StringBuilder sb) { return sb; } } It successfully adds the "blah" extension method to the StringBuilder. Unfortunately, operator overloading does not seem to work: public static class sbExtensions { public static StringBuilder operator +(this StringBuilder sb, string s) { return sb.Append(s); } } Among other issues, the keyword 'this' is not allowed in this context. Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?

    Read the article

  • C++ overloading virtual = operator

    - by taz
    Hello, here is the code for my question: class ICommon { public: virtual ICommon& operator=(const ICommon & p)const=0; }; class CSpecial : public ICommon { public: CSpecial& operator=(const CSpecial & cs) { //custom operations return *this; } }; CSpecial obj; Basically: I want the interface ICommon to force it's descendants to implement = operator but don't want to have any typecasts in the implementation. The compiler says "can't instantiate an abstract class. Any help/advice will be appreciated.

    Read the article

  • How do I write an overload operator where both arguments are interface

    - by Eric Girard
    I'm using interface for most of my stuff. I can't find a way to create an overload operator + that would allow me to perform an addition on any objects implementing the IPoint interface Code interface IPoint { double X { get; set; } double Y { get; set; } } class Point : IPoint { double X { get; set; } double Y { get; set; } //How and where do I create this operator/extension ??? public static IPoint operator + (IPoint a,IPoint b) { return Add(a,b); } public static IPoint Add(IPoint a,IPoint b) { return new Point { X = a.X + b.X, Y = a.Y + b.Y }; } } //Dumb use case : public class Test { IPoint _currentLocation; public Test(IPoint initialLocation) { _currentLocation = intialLocation } public MoveOf(IPoint movement) { _currentLocation = _currentLocation + intialLocation; //Much cleaner/user-friendly than _currentLocation = Point.Add(_currentLocation,intialLocation); } }

    Read the article

  • C++ operator overloading doubt

    - by avd
    I have a code base, in which for Matrix class, these two definitions are there for () operator: template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col) { ...... } template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const { ...... } One thing I understand is that the second one does not return the reference but what does const mean in the second declaration. Also which function is called when I do say mat(i,j)

    Read the article

  • Operator Overloading for Queue C++

    - by Josh
    I was trying to use the overload operator method to copy the entries of one queue into another, but I am going wrong with my function. I don't know how else to access the values of the queue "original" any other way than what I have below: struct Node { int item; Node* next; }; class Queue { public: [...] //Extra code here void operator = (const Queue &original); protected: Node *front, *end; } void Queue::operator=(const Queue &original) { //THIS IS WHERE IM GOING WRONG while(original.front->next != NULL) { front->item = original.front->item; front->next = new Node; front = front->next; original.front = original.front->next; } }

    Read the article

  • signature output operator overload

    - by coubeatczech
    hi, do you know, how to write signature of a function or method for operator<< for template class in C++? I want something like: template <class A class MyClass{ public: friend ostream & operator<<(ostream & os, MyClass<A mc); } ostream & operator<<(ostream & os, MyClass<A mc){ // some code return os; } But this just won't compile. Do anyone know, how to write it correctly?

    Read the article

  • Overloading assignment operator in C#

    - by Carson Myers
    I know the = operator can't be overloaded, but there must be a way to do what I want here: I'm just creating classes to represent quantitative units, since I'm doing a bit of physics. Apparently I can't just inherit from a primitive, but I want my classes to behave exactly like primitives -- I just want them typed differently. So I'd be able to go, Velocity ms = 0; ms = 17.4; ms += 9.8; etc. I'm not sure how to do this. I figured I'd just write some classes like so: class Power { private Double Value { get; set; } //operator overloads for +, -, /, *, =, etc } But apparently I can't overload the assignment operator. Is there any way I can get this behavior?

    Read the article

  • C++ operator[] syntax.

    - by Lanissum
    Just a quick syntax question. I'm writing a map class (for school). If I define the following operator overload: template<typename Key, typename Val> class Map {... Val* operator[](Key k); What happens when a user writes: Map<int,int> myMap; map[10] = 3; Doing something like that will only overwrite a temporary copy of the [null] pointer at Key k. Is it even possible to do: map[10] = 3; printf("%i\n", map[10]); with the same operator overload?

    Read the article

  • does overload operator-> a compile time action?

    - by Brent
    when I tried to compile the code: struct S { void func2() {} }; class O { public: inline S* operator->() const; private: S* ses; }; inline S* O::operator->() const { return ses; } int main() { O object; object->func(); return 0; } there is a compile error reported: D:\code>g++ operatorp.cpp -S -o operatorp.exe operatorp.cpp: In function `int main()': operatorp.cpp:27: error: 'struct S' has no member named 'func' it seems that invoke the overloaded function of "operator-" is done during compile time? I'd add "-S" option for compile only.

    Read the article

  • Problem using delete[] (Heap corruption) when implementing operator+= (C++)

    - by Darel
    I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong. I have written a simple class to emulate basic functionality of strings. The class's members include a character pointer data (which points to a dynamically created char array) and an integer strSize (which holds the length of the string, sans terminator.) Since I'm using new and delete, I've implemented the copy constructor and destructor. My problem occurs when I try to implement the operator+=. The LHS object builds the new string correctly - I can even print it using cout - but the problem comes when I try to deallocate the data pointer in the destructor: I get a "Heap Corruption Detected after normal block" at the memory address pointed to by the data array the destructor is trying to deallocate. Here's my complete class and test program: #include <iostream> using namespace std; // Class to emulate string class Str { public: // Default constructor Str(): data(0), strSize(0) { } // Constructor from string literal Str(const char* cp) { data = new char[strlen(cp) + 1]; char *p = data; const char* q = cp; while (*q) *p++ = *q++; *p = '\0'; strSize = strlen(cp); } Str& operator+=(const Str& rhs) { // create new dynamic memory to hold concatenated string char* str = new char[strSize + rhs.strSize + 1]; char* p = str; // new data char* i = data; // old data const char* q = rhs.data; // data to append // append old string to new string in new dynamic memory while (*p++ = *i++) ; p--; while (*p++ = *q++) ; *p = '\0'; // assign new values to data and strSize delete[] data; data = str; strSize += rhs.strSize; return *this; } // Copy constructor Str(const Str& s) { data = new char[s.strSize + 1]; char *p = data; char *q = s.data; while (*q) *p++ = *q++; *p = '\0'; strSize = s.strSize; } // destructor ~Str() { delete[] data; } const char& operator[](int i) const { return data[i]; } int size() const { return strSize; } private: char *data; int strSize; }; ostream& operator<<(ostream& os, const Str& s) { for (int i = 0; i != s.size(); ++i) os << s[i]; return os; } // Test constructor, copy constructor, and += operator int main() { Str s = "hello"; // destructor for s works ok Str x = s; // destructor for x works ok s += "world!"; // destructor for s gives error cout << s << endl; cout << x << endl; return 0; }

    Read the article

  • Binary operator overloading on a templated class (C++)

    - by GRB
    Hi all, I was recently trying to gauge my operator overloading/template abilities and as a small test, created the Container class below. While this code compiles fine and works correctly under MSVC 2008 (displays 11), both MinGW/GCC and Comeau choke on the operator+ overload. As I trust them more than MSVC, I'm trying to figure out what I'm doing wrong. Here is the code: #include <iostream> using namespace std; template <typename T> class Container { friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs); public: void setobj(T ob); T getobj(); private: T obj; }; template <typename T> void Container<T>::setobj(T ob) { obj = ob; } template <typename T> T Container<T>::getobj() { return obj; } template <typename T> Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) { Container<T> temp; temp.obj = lhs.obj + rhs.obj; return temp; } int main() { Container<int> a, b; a.setobj(5); b.setobj(6); Container<int> c = a + b; cout << c.getobj() << endl; return 0; } This is the error Comeau gives: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "ComeauTest.c", line 27: error: an explicit template argument list is not allowed on this declaration Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs) ^ 1 error detected in the compilation of "ComeauTest.c". I'm having a hard time trying to get Comeau/MingGW to play ball, so that's where I turn to you guys. It's been a long time since my brain has melted this much under the weight of C++ syntax, so I feel a little embarrassed ;). Thanks in advance. EDIT: Eliminated an (irrelevant) lvalue error listed in initial Comeau dump.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >