Search Results

Search found 2727 results on 110 pages for 'operator overloading'.

Page 8/110 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Are there supposed to be more restrictions on operator->* overloads?

    - by Potatoswatter
    I was perusing section 13.5 after refuting the notion that built-in operators do not participate in overload resolution, and noticed that there is no section on operator->*. It is just a generic binary operator. Its brethren, operator->, operator*, and operator[], are all required to be non-static member functions. This precludes definition of a free function overload to an operator commonly used to obtain a reference from an object. But the uncommon operator->* is left out. In particular, operator[] has many similarities. It is binary (they missed a golden opportunity to make it n-ary), and it accepts some kind of container on the left and some kind of locator on the right. Its special-rules section, 13.5.5, doesn't seem to have any actual effect except to outlaw free functions. (And that restriction even precludes support for commutativity!) So, for example, this is perfectly legal (in C++0x, remove obvious stuff to translate to C++03): #include <utility> #include <iostream> #include <type_traits> using namespace std; template< class F, class S > typename common_type< F,S >::type operator->*( pair<F,S> const &l, bool r ) { return r? l.second : l.first; } template< class T > T & operator->*( pair<T,T> &l, bool r ) { return r? l.second : l.first; } template< class T > T & operator->*( bool l, pair<T,T> &r ) { return l? r.second : r.first; } int main() { auto x = make_pair( 1, 2.3 ); cerr << x->*false << " " << x->*4 << endl; auto y = make_pair( 5, 6 ); y->*(0) = 7; y->*0->*y = 8; // evaluates to 7->*y = y.second cerr << y.first << " " << y.second << endl; } I can certainly imagine myself giving into temp[la]tation. For example, scaled indexes for vector: v->*matrix_width[5] = x; Did the standards committee forget to prevent this, was it considered too ugly to bother, or are there real-world use cases?

    Read the article

  • Templated << friend not working when in interrelationship with other templated union types

    - by Dwight
    While working on my basic vector library, I've been trying to use a nice syntax for swizzle-based printing. The problem occurs when attempting to print a swizzle of a different dimension than the vector in question. In GCC 4.0, I originally had the friend << overloaded functions (with a body, even though it duplicated code) for every dimension in each vector, which caused the code to work, even if the non-native dimension code never actually was called. This failed in GCC 4.2. I recently realized (silly me) that only the function declaration was needed, not the body of the code, so I did that. Now I get the same warning on both GCC 4.0 and 4.2: LINE 50 warning: friend declaration 'std::ostream& operator<<(std::ostream&, const VECTOR3<TYPE>&)' declares a non-template function Plus the five identical warnings more for the other function declarations. The below example code shows off exactly what's going on and has all code necessary to reproduce the problem. #include <iostream> // cout, endl #include <sstream> // ostream, ostringstream, string using std::cout; using std::endl; using std::string; using std::ostream; // Predefines template <typename TYPE> union VECTOR2; template <typename TYPE> union VECTOR3; template <typename TYPE> union VECTOR4; typedef VECTOR2<float> vec2; typedef VECTOR3<float> vec3; typedef VECTOR4<float> vec4; template <typename TYPE> union VECTOR2 { private: struct { TYPE x, y; } v; struct s1 { protected: TYPE x, y; }; struct s2 { protected: TYPE x, y; }; struct s3 { protected: TYPE x, y; }; struct s4 { protected: TYPE x, y; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR2() {} VECTOR2(const TYPE& x, const TYPE& y) { v.x = x; v.y = y; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); }; template <typename TYPE> union VECTOR3 { private: struct { TYPE x, y, z; } v; struct s1 { protected: TYPE x, y, z; }; struct s2 { protected: TYPE x, y, z; }; struct s3 { protected: TYPE x, y, z; }; struct s4 { protected: TYPE x, y, z; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR3() {} VECTOR3(const TYPE& x, const TYPE& y, const TYPE& z) { v.x = x; v.y = y; v.z = z; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ", " << toString.v.z << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); }; template <typename TYPE> union VECTOR4 { private: struct { TYPE x, y, z, w; } v; struct s1 { protected: TYPE x, y, z, w; }; struct s2 { protected: TYPE x, y, z, w; }; struct s3 { protected: TYPE x, y, z, w; }; struct s4 { protected: TYPE x, y, z, w; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR4() {} VECTOR4(const TYPE& x, const TYPE& y, const TYPE& z, const TYPE& w) { v.x = x; v.y = y; v.z = z; v.w = w; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR4& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ", " << toString.v.z << ", " << toString.v.w << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); }; // Test code int main (int argc, char * const argv[]) { vec2 my2dVector(1, 2); cout << my2dVector.x << endl; cout << my2dVector.xx << endl; cout << my2dVector.xxx << endl; cout << my2dVector.xxxx << endl; vec3 my3dVector(3, 4, 5); cout << my3dVector.x << endl; cout << my3dVector.xx << endl; cout << my3dVector.xxx << endl; cout << my3dVector.xxxx << endl; vec4 my4dVector(6, 7, 8, 9); cout << my4dVector.x << endl; cout << my4dVector.xx << endl; cout << my4dVector.xxx << endl; cout << my4dVector.xxxx << endl; return 0; } The code WORKS and produces the correct output, but I prefer warning free code whenever possible. I followed the advice the compiler gave me (summarized here and described by forums and StackOverflow as the answer to this warning) and added the two things that supposedly tells the compiler what's going on. That is, I added the function definitions as non-friends after the predefinitions of the templated unions: template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); And, to each friend function that causes the issue, I added the <> after the function name, such as for VECTOR2's case: friend ostream& operator<< <> (ostream& os, const VECTOR3<TYPE>& toString); friend ostream& operator<< <> (ostream& os, const VECTOR4<TYPE>& toString); However, doing so leads to errors, such as: LINE 139: error: no match for 'operator<<' in 'std::cout << my2dVector.VECTOR2<float>::xxx' What's going on? Is it something related to how these templated union class-like structures are interrelated, or is it due to the unions themselves? Update After rethinking the issues involved and listening to the various suggestions of Potatoswatter, I found the final solution. Unlike just about every single cout overload example on the internet, I don't need access to the private member information, but can use the public interface to do what I wish. So, I make a non-friend overload functions that are inline for the swizzle parts that call the real friend overload functions. This bypasses the issues the compiler has with templated friend functions. I've added to the latest version of my project. It now works on both versions of GCC I tried with no warnings. The code in question looks like this: template <typename SWIZZLE> inline typename EnableIf< Is2D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; } template <typename SWIZZLE> inline typename EnableIf< Is3D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; } template <typename SWIZZLE> inline typename EnableIf< Is4D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; }

    Read the article

  • How do I go about overloading C++ operators to allow for chaining?

    - by fneep
    I, like so many programmers before me, am tearing my hair out writing the right-of-passage-matrix-class-in-C++. I have never done very serious operator overloading and this is causing issues. Essentially, by stepping through This is what I call to cause the problems. cMatrix Kev = CT::cMatrix::GetUnitMatrix(4, true); Kev *= 4.0f; cMatrix Baz = Kev; Kev = Kev+Baz; //HERE! What seems to be happening according to the debugger is that Kev and Baz are added but then the value is lost and when it comes to reassigning to Kev, the memory is just its default dodgy values. How do I overload my operators to allow for this statement? My (stripped down) code is below. //header class cMatrix { private: float* _internal; UInt32 _r; UInt32 _c; bool _zeroindexed; //fast, assumes zero index, no safety checks float cMatrix::_getelement(UInt32 r, UInt32 c) { return _internal[(r*this->_c)+c]; } void cMatrix::_setelement(UInt32 r, UInt32 c, float Value) { _internal[(r*this->_c)+c] = Value; } public: cMatrix(UInt32 r, UInt32 c, bool IsZeroIndexed); cMatrix( cMatrix& m); ~cMatrix(void); //operators cMatrix& operator + (cMatrix m); cMatrix& operator += (cMatrix m); cMatrix& operator = (const cMatrix &m); }; //stripped source file cMatrix::cMatrix(cMatrix& m) { _r = m._r; _c = m._c; _zeroindexed = m._zeroindexed; _internal = new float[_r*_c]; UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] = m._internal[i]; } } cMatrix::~cMatrix(void) { delete[] _internal; } cMatrix& cMatrix::operator+(cMatrix m) { return cMatrix(*this) += m; } cMatrix& cMatrix::operator*(float f) { return cMatrix(*this) *= f; } cMatrix& cMatrix::operator*=(float f) { UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] *= f; } return *this; } cMatrix& cMatrix::operator+=(cMatrix m) { if (_c != m._c || _r != m._r) { throw new cCTException("Cannot add two matrix classes of different sizes."); } if (!(_zeroindexed && m._zeroindexed)) { throw new cCTException("Zero-Indexed mismatch."); } for (UInt32 row = 0; row < _r; row++) { for (UInt32 column = 0; column < _c; column++) { float Current = _getelement(row, column) + m._getelement(row, column); _setelement(row, column, Current); } } return *this; } cMatrix& cMatrix::operator=(const cMatrix &m) { if (this != &m) { _r = m._r; _c = m._c; _zeroindexed = m._zeroindexed; delete[] _internal; _internal = new float[_r*_c]; UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] = m._internal[i]; } } return *this; }

    Read the article

  • Operator== in derived class never gets called.

    - by Robin Welch
    Can someone please put me out of my misery with this? I'm trying to figure out why a derived operator== never gets called in a loop. To simplify the example, here's my Base and Derived class: class Base { // ... snipped bool operator==( const Base& other ) const { return name_ == other.name_; } }; class Derived : public Base { // ... snipped bool operator==( const Derived& other ) const { return ( static_cast<const Base&>( *this ) == static_cast<const Base&>( other ) ? age_ == other.age_ : false ); }; Now when I instantiate and compare like this ... Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 ); ... all is fine. Here the operator== from Derived gets called, but when I loop over a list, comparing items in a list of pointers to Base objects ... list<Base*> coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base& obj1 = **itr; Base& obj2 = **itr2; cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " " << obj2.asString() << endl; Here asString() (which is virtual and not shown here for brevity) works fine, but obj1 == obj2 always calls the Base operator== even if the two objects are Derived. I know I'm going to kick myself when I find out what's wrong, but if someone could let me down gently it would be much appreciated.

    Read the article

  • F# operator over-loading question

    - by jyoung
    The following code fails in 'Evaluate' with: "This expression was expected to have type Complex but here has type double list" Am I breaking some rule on operator over-loading on '(+)'? Things are OK if I change '(+)' to 'Add'. open Microsoft.FSharp.Math /// real power series [kn; ...; k0] => kn*S^n + ... + k0*S^0 type Powers = double List let (+) (ls:Powers) (rs:Powers) = let rec AddReversed (ls:Powers) (rs:Powers) = match ( ls, rs ) with | ( l::ltail, r::rtail ) -> ( l + r ) :: AddReversed ltail rtail | ([], _) -> rs | (_, []) -> ls ( AddReversed ( ls |> List.rev ) ( rs |> List.rev) ) |> List.rev let Evaluate (ks:Powers) ( value:Complex ) = ks |> List.fold (fun (acc:Complex) (k:double)-> acc * value + Complex.Create(k, 0.0) ) Complex.Zero

    Read the article

  • Java operator overloading

    - by nimcap
    Not using operators makes my code obscure. (aNumber / aNother) * count is better than aNumber.divideBy(aNother).times(count) After 6 months of not writing a single comment I had to write a comment to the simple operation above. Usually I refactor until I don't need comment. And this made me realize that it is easier to read and perceive math symbols and numbers than their written forms. For example TWENTY_THOUSAND_THIRTEEN.plus(FORTY_TWO.times(TWO_HUNDERED_SIXTY_ONE)) is more obscure than 20013 + 42*261 So do you know a way to get rid of obscurity while not using operator overloading in Java? Update: I did not think my exaggeration on comments would cause such trouble to me. I am admitting that I needed to write comment a couple of times in 6 months. But not more than 10 lines in total. Sorry for that. Update 2: Another example: budget.plus(bonusCoefficient.times(points)) is more obscure than budget + bonusCoefficient * points I have to stop and think on the first one, at first sight it looks like clutter of words, on the other hand, I get the meaning at first look for the second one, it is very clear and neat. I know this cannot be achieved in Java but I wanted to hear some ideas about my alternatives.

    Read the article

  • Efficiency of manually written loops vs operator overloads (C++)

    - by Sagekilla
    Hi all, in the program I'm working on I have 3-element arrays, which I use as mathematical vectors for all intents and purposes. Through the course of writing my code, I was tempted to just roll my own Vector class with simple +, -, *, /, etc overloads so I can simplify statements like: for (int i = 0; i < 3; i++) r[i] = r1[i] - r2[i]; // becomes: r = r1 - r2; Which should be more or less identical in generated code. But when it comes to more complicated things, could this really impact my performance heavily? One example that I have in my code is this: Manually written version: for (int j = 0; j < 3; j++) { p.vel[j] = p.oldVel[j] + (p.oldAcc[j] + p.acc[j]) * dt2 + (p.oldJerk[j] - p.jerk[j]) * dt12; p.pos[j] = p.oldPos[j] + (p.oldVel[j] + p.vel[j]) * dt2 + (p.oldAcc[j] - p.acc[j]) * dt12; } Using a Vector class with operator overloads: p.vel = p.oldVel + (p.oldAcc + p.acc) * dt2 + (p.oldJerk - p.jerk) * dt12; p.pos = p.oldPos + (p.oldVel + p.vel) * dt2 + (p.oldAcc - p.acc) * dt12; I am compiling my code for maximum possible speed, as it's extremely important that this code runs quickly and calculates accurately. So will me relying on my Vector's for these sorts of things really affect me? For those curious, this is part of some numerical integration code which is not trivial to run in my program. Any insight would be appreciated, as would any idioms or tricks I'm unaware of.

    Read the article

  • C++ template class error with operator ==

    - by Tommy
    Error: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion) The function: template <class T, int maxSize> int indexList<T, maxSize>::search(const T& target) const { for (int i = 0; i < maxSize; i++) if (elements[i] == target) //ERROR??? return i; // target found at position i // target not found return -1; } indexList.h indexList.cpp Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error? Solution- The overload function in the class now declared const: //Operators bool entry::operator == (const entry& dE) const <-- { return (name ==dE.name); }

    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

  • C# implicit conversions and == operator

    - by Arnis L.
    Some code for context: class a { } class b { public a a{get;set;} public static implicit operator a(b b) { return b.a; } } a a=null; b b=null; a = b; //compiler: cannot apply operator '==' to operands of type tralala... bool c = a == b; Is it possible to use == operator on different type instances, where one can implicitly convert to another? What did i miss? Edit: If types must be the same calling ==, then why int a=1; double b=1; bool c=a==b; works?

    Read the article

  • C++ OOP - Can you 'overload a cast' <- hard to explain in 1 sentence

    - by Brandon Miller
    Well, the WinAPI has a POINT struct, but I am trying to make an alternative class to this so you can set the values of x and y from a constructor. /** * X-Y coordinates */ class Point { public: int X, Y; Point(void) : X(0), Y(0) {} Point(int x, int y) : X(x), Y(y) {} Point(const POINT& pt) : X(pt.x), Y(pt.y) {} Point& operator= (const POINT& other) { X = other.x; Y = other.y; } }; // I have an assignment operator and copy constructor. Point myPtA(3,7); Point myPtB(8,5); POINT pt; pt.x = 9; pt.y = 2; // I can assign a 'POINT' to a 'Point' myPtA = pt; // But I also want to be able to assign a 'Point' to a 'POINT' pt = myPtB; Is it possible to overload operator= in a way so that I can assign a Point to a POINT? Or maybe some other method to achieve this? Thanks in advance.

    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

  • Java == operator. "Invalid assignment operator"

    - by Tom
    Hi, I was trying to write a simple method boolean validate(MyObject o) { return o.getPropertyA() == null && o.getPropertyB()==null; } And got a strange error on the == null part. Maybe my Java is rusty after a season in PLSQL. Consider this: Integer i = 4; i ==null; //compile error: Syntax error on token ==. Invalid assignment operator. Integer i2 = 4; if (i==null); //No problem How can this be ? Any explanation ? Im using jdk160_05.

    Read the article

  • C# what does the == operator do in detail?

    - by clamp
    in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? does it just compare the addresses? or does it something like Equals() or CompareTo() ? PS: what about the "==" operator in java? does it behave the same?

    Read the article

  • JavaScript: using constructor without operator 'new'

    - by GetFree
    Please help me to understand why the following code works: <script> var re = RegExp('\\ba\\b') ; alert(re.test('a')) ; alert(re.test('ab')) ; </script> In the first line there is no new operator. As far as I know, a contructor in JavaScript is a function that initialize objects created by the operator new and they are not meant to return anything.

    Read the article

  • Assignment operator that calls a constructor is broken

    - by Delan Azabani
    I've implemented some of the changes suggested in this question, and (thanks very much) it works quite well, however... in the process I've seemed to break the post-declaration assignment operator. With the following code: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } I get a nice "testing cafe´" message. However, if I modify the code slightly so that the const char * conversion is done separately, post-declaration: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d; d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } the ustring named d becomes blank, and all that is output is "testing ". My new code has three constructors, one void (which is probably the one being incorrectly used, and is used in the operator+ function), one that takes a const ustring &, and one that takes a const char *. The following is my new library code: #include <cstdlib> #include <cstring> class ustring { int * values; long len; public: long length() { return len; } ustring() { len = 0; values = (int *) malloc(0); } ustring(const ustring &input) { len = input.len; values = (int *) malloc(sizeof(int) * len); for (long i = 0; i < len; i++) values[i] = input.values[i]; } ustring operator=(ustring input) { ustring result(input); return result; } ustring(const char * input) { values = (int *) malloc(0); long s = 0; // s = number of parsed chars int a, b, c, d, contNeed = 0, cont = 0; for (long i = 0; input[i]; i++) if (input[i] < 0x80) { // ASCII, direct copy (00-7f) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = input[i]; } else if (input[i] < 0xc0) { // this is a continuation (80-bf) if (cont == contNeed) { // no need for continuation, use U+fffd values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } cont = cont + 1; values[s - 1] = values[s - 1] | ((input[i] & 0x3f) << ((contNeed - cont) * 6)); if (cont == contNeed) cont = contNeed = 0; } else if (input[i] < 0xc2) { // invalid byte, use U+fffd (c0-c1) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } else if (input[i] < 0xe0) { // start of 2-byte sequence (c2-df) contNeed = 1; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x1f) << 6; } else if (input[i] < 0xf0) { // start of 3-byte sequence (e0-ef) contNeed = 2; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x0f) << 12; } else if (input[i] < 0xf5) { // start of 4-byte sequence (f0-f4) contNeed = 3; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x07) << 18; } else { // restricted or invalid (f5-ff) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } len = s; } ustring operator=(const char * input) { ustring result(input); return result; } ustring operator+(ustring input) { ustring result; result.len = len + input.len; result.values = (int *) malloc(sizeof(int) * result.len); for (long i = 0; i < len; i++) result.values[i] = values[i]; for (long i = 0; i < input.len; i++) result.values[i + len] = input.values[i]; return result; } ustring operator[](long index) { ustring result; result.len = 1; result.values = (int *) malloc(sizeof(int)); result.values[0] = values[index]; return result; } char * encode() { char * r = (char *) malloc(0); long s = 0; for (long i = 0; i < len; i++) { if (values[i] < 0x80) r = (char *) realloc(r, s + 1), r[s + 0] = char(values[i]), s += 1; else if (values[i] < 0x800) r = (char *) realloc(r, s + 2), r[s + 0] = char(values[i] >> 6 | 0x60), r[s + 1] = char(values[i] & 0x3f | 0x80), s += 2; else if (values[i] < 0x10000) r = (char *) realloc(r, s + 3), r[s + 0] = char(values[i] >> 12 | 0xe0), r[s + 1] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 2] = char(values[i] & 0x3f | 0x80), s += 3; else r = (char *) realloc(r, s + 4), r[s + 0] = char(values[i] >> 18 | 0xf0), r[s + 1] = char(values[i] >> 12 & 0x3f | 0x80), r[s + 2] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 3] = char(values[i] & 0x3f | 0x80), s += 4; } return r; } };

    Read the article

  • Negate the null-coalescing operator

    - by jhunter
    I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like: string endString = startString !?? startString.Trim(); Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?

    Read the article

  • behaviour of the implicit copy constructor / assignment operator

    - by Tobias Langner
    Hello, I have a question regarding the C++ Standard. Suppose you have a base class with user defined copy constructor and assignment operator. The derived class uses the implicit one generated by the compiler. Does copying / assignment of the derived class call the user defined copy constructor / assignment operator? Or do you need to implement user defined versions that call the base class? Thank you for your help.

    Read the article

  • C++ segmentation error when first parameter is null in comparison operator overload

    - by user1774515
    I am writing a class called Word, that handles a c string and overloads the <, , <=, = operators. word.h: friend bool operator<(const Word &a, const Word &b); word.cc: bool operator<(const Word &a, const Word &b) { if(a == NULL && b == NULL) return false; if(a == NULL) return true; if(b == NULL) return false; return a.wd < b.wd; //wd is a valid c string } main: char* temp = NULL; //EDIT: i was mistaken, temp is a char pointer Word a("blah"); //a.wd = [b,l,a,h] cout << (temp<a); i get a segmentation error before the first line of the operator< method after the last line in the main. I can correct the problem by writing cout << (a>temp); where the operator> is similarly defined and i get no errors. but my assignment requires (temp < a) to work so this is where i ask for help. EDIT: i made a mistake the first time and i said temp was of type Word, but it is actually of type char*. so i assume that the compiler converts temp to a Word using one of my constructors. i dont know which one it would use and why this would work since the first parameter is not Word. here is the constructor i think is being used to make the Word using temp: Word::Word(char* c, char* delimeters=NULL) { char *temporary = "\0"; if(c == NULL) c = temporary; check(stoppers!=NULL, "(Word(char*,char*))NULL pointer"); //exits the program if the expression is false if(strlen(c) == 0) size = DEFAULT_SIZE; //10 else size = strlen(c) + 1 + DEFAULT_SIZE; wd = new char[size]; check(wd!=NULL, "Word(char*,char*))heap overflow"); delimiters = new char[strlen(stoppers) + 1]; //EDIT: changed to [] check(delimiters!=NULL,"Word(char*,char*))heap overflow"); strcpy(wd,c); strcpy(delimiters,stoppers); count = strlen(wd); } wd is of type char* thanks for looking at this big question and trying to help. let me know if you need more code to look at

    Read the article

  • How to push_back without operator=() for const members?

    - by WilliamKF
    How to push_back() to a C++ std::vector without using operator=() for which the default definition violates having const members? struct Item { Item(int value) : _value(value) { } const int _value; } vector<Item> items; items.push_back(Item(3)); I'd like to keep the _value const since it should not change after the object is constructed, so the question is how do I initialize my vector with elements without invoking operator=()?

    Read the article

  • 3x3 Sobel operator and gradient features

    - by pithyless
    Reading a paper, I'm having difficulty understanding the algorithm described: Given a black and white digital image of a handwriting sample, cut out a single character to analyze. Since this can be any size, the algorithm needs to take this into account (if it will be easier, we can assume the size is 2^n x 2^m). Now, the description states given this image we will convert it to a 512-bit feature (a 512-bit hash) as follows: (192 bits) computes the gradient of the image by convolving it with a 3x3 Sobel operator. The direction of the gradient at every edge is quantized to 12 directions. (192 bits) The structural feature generator takes the gradient map and looks in a neighborhood for certain combinations of gradient values. (used to compute 8 distinct features that represent lines and corners in the image) (128 bits) Concavity generator uses an 8-point star operator to find coarse concavities in 4 directions, holes, and lagrge-scale strokes. The image feature maps are normalized with a 4x4 grid. I'm for now struggling with how to take an arbitrary image, split into 16 sections, and using a 3x3 Sobel operator to come up with 12 bits for each section. (But if you have some insight into the other parts, feel free to comment :)

    Read the article

  • operator<< overload,

    - by mr.low
    //using namespace std; using std::ifstream; using std::ofstream; using std::cout; class Dog { friend ostream& operator<< (ostream&, const Dog&); public: char* name; char* breed; char* gender; Dog(); ~Dog(); }; im trying to overload the << operator. I'm also trying to practice good coding. But my code wont compile unless i uncomment the using namespace std. i keep getting this error and i dont know. im using g++ compiler. Dog.h:20: error: ISO C++ forbids declaration of ‘ostream’ with no type Dog.h:20: error: ‘ostream’ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error. Dog.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type. Can somebody tell me the correct way to overload the << operator with out using namespace std;

    Read the article

  • Providing less than operator for one element of a pair

    - by Koszalek Opalek
    What would be the most elegant way too fix the following code: #include <vector> #include <map> #include <set> using namespace std; typedef map< int, int > row_t; typedef vector< row_t > board_t; typedef row_t::iterator area_t; bool operator< ( area_t const& a, area_t const& b ) { return( a->first < b->first ); }; int main( int argc, char* argv[] ) { int row_num; area_t it; set< pair< int, area_t > > queue; queue.insert( make_pair( row_num, it ) ); // does not compile }; One way to fix it is moving the definition of less< to namespace std (I know, you are not supposed to do it.) namespace std { bool operator< ( area_t const& a, area_t const& b ) { return( a->first < b->first ); }; }; Another obvious solution is defining less than< for pair< int, area_t but I'd like to avoid that and be able to define the operator only for the one element of the pair where it is not defined.

    Read the article

  • Assigning a vector of one type to a vector of another type

    - by deworde
    Hi, I have an "Event" class. Due to the way dates are handled, we need to wrap this class in a "UIEvent" class, which holds the Event, and the date of the Event in another format. What is the best way of allowing conversion from Event to UIEvent and back? I thought overloading the assignment or copy constructor of UIEvent to accept Events (and vice versa)might be best.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >