Search Results

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

Page 16/110 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • friendship and operator overloading help

    - by sil3nt
    hello there, I have the following class #ifndef Container_H #define Container_H #include <iostream> using namespace std; class Container{ friend bool operator==(const Container &rhs,const Container &lhs); public: void display(ostream & out) const; private: int sizeC; // size of Container int capacityC; // capacity of dynamic array int * elements; // pntr to dynamic array }; ostream & operator<< (ostream & out, const Container & aCont); #endif and this source file #include "container.h" /*----------------------------********************************************* note: to test whether capacityC and sizeC are equal, must i add 1 to sizeC? seeing as sizeC starts off with 0?? */ Container::Container(int maxCapacity){ capacityC = maxCapacity; elements = new int [capacityC]; sizeC = 0; } Container::~Container(){ delete [] elements; } Container::Container(const Container & origCont){ //copy constructor? int i = 0; for (i = 0; i<capacityC; i++){ //capacity to be used here? (*this).elements[i] = origCont.elements[i]; } } bool Container::empty() const{ if (sizeC == 0){ return true; }else{ return false; } } void Container::insert(int item, int index){ if ( sizeC == capacityC ){ cout << "\n*** Next: Bye!\n"; return; // ? have return here? } if ( (index >= 0) && (index <= capacityC) ){ elements[index] = item; sizeC++; } if ( (index < 0) && (index > capacityC) ){ cout<<"*** Illegal location to insert--"<< index << ". Container unchanged. ***\n"; }//error here not valid? according to original a3? have i implemented wrong? } void Container::erase(int index){ if ( (index >= 0) && (index <= capacityC) ){ //correct here? legal location? int i = 0; while (i<capacityC){ //correct? elements[index] = elements[index+1]; //check if index increases here. i++; } sizeC=sizeC-1; //correct? updated sizeC? }else{ cout<<"*** Illegal location to be removed--"<< index << ". Container unchanged. ***\n"; } } int Container::size()const{ return sizeC; //correct? } /* bool Container::operator==(const Container &rhs,const Container &lhs){ int equal = 0, i = 0; for (i = 0; i < capacityC ; i++){ if ( rhs.elements[i] == lhs.elements[i] ){ equal++; } } if (equal == sizeC){ return true; }else{ return false; } } ostream & operator<< (ostream & out, const Container & aCont){ int i = 0; for (i = 0; i<sizeC; i++){ out<< aCont.elements[i] << " " << endl; } } */ I dont have the other functions in the header file (just a quikie). Anyways, the last two functions in "/* */" I cant get to work, what am I doing wrong here? the first function is to see whether the two arrays are equal to one another

    Read the article

  • subclassing QList and operator+ overloading

    - by Milen
    I would like to be able to add two QList objects. For example: QList<int> b; b.append(10); b.append(20); b.append(30); QList<int> c; c.append(1); c.append(2); c.append(3); QList<int> d; d = b + c; For this reason, I decided to subclass the QList and to overload the operator+. Here is my code: class List : public QList<int> { public: List() : QList<int>() {} // Add QList + QList friend List operator+(const List& a1, const List& a2); }; List operator+(const List& a1, const List& a2) { List myList; myList.append(a1[0] + a2[0]); myList.append(a1[1] + a2[1]); myList.append(a1[2] + a2[2]); return myList; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); List b; b.append(10); b.append(20); b.append(30); List c; c.append(1); c.append(2); c.append(3); List d; d = b + c; List::iterator i; for(i = d.begin(); i != d.end(); ++i) qDebug() << *i; return a.exec(); } , the result is correct but I am not sure whether this is a good approach. I would like to ask whether there is better solution?

    Read the article

  • cons operator (::) in F#

    - by Max
    The :: operator in F# always prepends elements to the list. Is there an operator that appends to the list? I'm guessing that using @ operator [1; 2; 3] @ [4] would be less efficient, than appending one element.

    Read the article

  • Adding two different Objects by overloading operator+ C++

    - by lampshade
    Hello, I've been trying to figure out how to add a private member from Object A, to a private member from Object B. Both Cat and Dog Class's inheriate from the base class Animal. I have a thrid class 'MyClass', that I want to inheriate the private members of the Cat and Dog class. So in MyClass, I have a friend function to overload the + operator. THe friend function is defined as follows: MyClass operator+(const Dog &dObj, const Cat &cObj); I want to access dObj.age and cObj.age within the above function, invoke by this statement in main: mObj = dObj + cObj; Here is the entire source for a complete reference into the class objects: #include <iostream> #include <vld.h> using namespace std; class Animal { public : Animal() {}; virtual void eat() = 0 {}; virtual void walk() = 0 {}; }; class Dog : public Animal { public : Dog(const char * name, const char * gender, int age); Dog() : name(NULL), gender(NULL), age(0) {}; virtual ~Dog(); void eat(); void bark(); void walk(); private : char * name; char * gender; int age; }; class Cat : public Animal { public : Cat(const char * name, const char * gender, int age); Cat() : name(NULL), gender(NULL), age(0) {}; virtual ~Cat(); void eat(); void meow(); void walk(); private : char * name; char * gender; int age; }; class MyClass : private Cat, private Dog { public : MyClass() : action(NULL) {}; void setInstance(Animal &newInstance); void doSomething(); friend MyClass operator+(const Dog &dObj, const Cat &cObj); private : Animal * action; }; Cat::Cat(const char * name, const char * gender, int age) : name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age) { if (name) { size_t length = strlen(name) +1; strcpy_s(this->name, length, name); } else name = NULL; if (gender) { size_t length = strlen(gender) +1; strcpy_s(this->gender, length, gender); } else gender = NULL; if (age) { this->age = age; } } Cat::~Cat() { delete name; delete gender; age = 0; } void Cat::walk() { cout << name << " is walking now.. " << endl; } void Cat::eat() { cout << name << " is eating now.. " << endl; } void Cat::meow() { cout << name << " says meow.. " << endl; } Dog::Dog(const char * name, const char * gender, int age) : name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age) { if (name) { size_t length = strlen(name) +1; strcpy_s(this->name, length, name); } else name = NULL; if (gender) { size_t length = strlen(gender) +1; strcpy_s(this->gender, length, gender); } else gender = NULL; if (age) { this->age = age; } } Dog::~Dog() { delete name; delete gender; age = 0; } void Dog::eat() { cout << name << " is eating now.. " << endl; } void Dog::bark() { cout << name << " says woof.. " << endl; } void Dog::walk() { cout << name << " is walking now.." << endl; } void MyClass::setInstance(Animal &newInstance) { action = &newInstance; } void MyClass::doSomething() { action->walk(); action->eat(); } MyClass operator+(const Dog &dObj, const Cat &cObj) { MyClass A; //dObj.age; //cObj.age; return A; } int main() { MyClass mObj; Dog dObj("B", "Male", 4); Cat cObj("C", "Female", 5); mObj.setInstance(dObj); // set the instance specific to the object. mObj.doSomething(); // something happens based on which object is passed in dObj.bark(); mObj.setInstance(cObj); mObj.doSomething(); cObj.meow(); mObj = dObj + cObj; return 0; }

    Read the article

  • Binary Tree operator overloading and recursion

    - by furious.snail
    I was wondering how to overload the == operator for a binary tree to compare if two trees have identical data at same nodes. So far this is what I have: bool TreeType::operator==(const TreeType& otherTree) const { if((root == NULL) && (otherTree.root == NULL)) return true; //two null trees are equal else if((root != NULL) && (otherTree.root != NULL)) { return((root-info == otherTree.root-info) && //this part doesn't actually do anything recursively... //(root-left == otherTree.root-left) && //(root-right == otherTree.root-right)) } else return false; //one tree is null the other is not } I have a similar function that takes two TreeNode pointers as parameters but I've been stuck on how to convert it to this function.

    Read the article

  • Overloading operator>> for case insensitive string

    - by TheSOFan
    Given the definition of ci_string from cpp.reference.com, how would we go about implementing operator? My attempts at it involved std::read, but it doesn't seem to work (that is, gcount() properly counts the number of characters entered, but there is no output) #include <iostream> #include <cctype> #include <string> // ci_string definition goes here std::istream& operator>>(std::istream& in, ci_string& str) { return in.read(&*str.begin(), 4); } int main() { ci_string test_str; std::cin >> test_str; std::cout << test_str; return 0; }

    Read the article

  • override the operator overloading in C++ ?

    - by stdnoit
    helo guys i have class call Complex I did operator overloading like such Complex c = a + b; // where a and b are object of Complex class which basically is operator+(Complex& that); but I dont know how to say for example double c = a + 10; //where a is object of Complex class but 10 is integer / double I did define typecasting for a to be double get my IDE says that there are too many operands + and it somehow complains for not being able to "understand" the + it has to be in this format though double c = a + 10; thanks

    Read the article

  • what is this operator called and what is it used for <=>

    - by Scott
    I recently came across this magical operator when digging into Groovy: <= Groovy has really made me happy with elvis operators ?. and ?: which I use constantly now and very much wish were in Java. With this new operator, I have only found this reference. It seems to make comparators much easier. My question is how does it handle null values and how does it compare non Comparable object. Does this operator have a name, I couldn't find it Googling.

    Read the article

  • overloading new operator in c++

    - by Angus
    I have a code for best fit algorithm. I want to try to use the best fit algorithm using the operator new. Every time I create an object I should give it from the already allocated memory say, 1]20 2]12 3]15 4]6 5]23 respectively. which ever minimum amount fits to the objects size(eg.21) I wanted to do it for different object types, so I need to write the overloaded operator new to be common functionality for all the class objects. Can I do it through friend functions, or is there any possible way to do it.

    Read the article

  • Abstract class and operator!= in c++

    - by Alessandro Teruzzi
    Hi All, I have problem implementing the operator!= in a set class deriving from an abstact one. The code looks like this: class Abstract { public: //to make the syntax easier let's use a raw pointer virtual bool operator!=(const Abstract* other) = 0; }; class Implementation { SomeObject impl_; //that already implement the operator!= public: bool operator!=(const Abstract* other) { return dynamic_cast<Implementation*>(other)->impl_ != this->impl_; } }; This code works but it has the drawback to use dynamic_cast and I need to handle error in casting operation. This is a generic problem that occur when a function of a concrete class it is trying to using some internal information (not available at the abstract class level) to perform a task. Is there any better way to solve this kind of problem? Cheers

    Read the article

  • Problem with std::map and std::pair

    - by Tom
    Hi everyone. I have a small program I want to execute to test something #include <map> #include <iostream> using namespace std; struct _pos{ float xi; float xf; bool operator<(_pos& other){ return this->xi < other.xi; } }; struct _val{ float f; }; int main() { map<_pos,_val> m; struct _pos k1 = {0,10}; struct _pos k2 = {10,15}; struct _val v1 = {5.5}; struct _val v2 = {12.3}; m.insert(std::pair<_pos,_val>(k1,v1)); m.insert(std::pair<_pos,_val>(k2,v2)); return 0; } The problem is that when I try to compile it, I get the following error $ g++ m2.cpp -o mtest In file included from /usr/include/c++/4.4/bits/stl_tree.h:64, from /usr/include/c++/4.4/map:60, from m2.cpp:1: /usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’: /usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ /usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ m2.cpp:30: instantiated from here /usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’ m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&) $ I thought that declaring the operator< on the key would solve the problem, but its still there. What could be wrong? Thanks in advance.

    Read the article

  • Overriding or overloading?

    - by atch
    Guys I know this question is silly but just to make sure: Having in my class method: boolean equal(Document d) { //do something } I'm overloading this method nor overriding right? I know that this or similiar question will be on upcoming egzam and would be stupid to not get points for such a simple mistake;

    Read the article

  • Function overloading

    - by makcoozi
    I found this code , and i m not sure that whether overloading should happen or not. void print( int (*arr)[6], int size ); void print( int (*arr)[5], int size ); what happens if I pass pointer to an array of 4 elements , to it should come... any thread will be helpful.

    Read the article

  • Linux's best filesystem to work with 10000's of files without overloading the system I/O

    - by mhambra
    Hi all. It is known that certain AMD64 Linuxes are subject of being unresponsive under heavy disk I/O (see Gentoo forums: AMD64 system slow/unresponsive during disk access (Part 2)), unfortunately have such one. I want to put /var/tmp/portage and /usr/portage trees to a separate partition, but what FS to choose for it? Requirements: * for journaling, performance is preffered over safe data read/write operations * optimized to read/write 10000 of small files Candidates: * ext2 without any journaling * BtrFS In Phoronix tests, BtrFS had demonstrated a good random access performance (fat better than XFS thereby it may be less CPU-aggressive). However, unpacking operation seems to be faster with XFS there, but it was tested that unpacking kernel tree to XFS makes my system to react slower for 51% disregard of any renice'd processes and/or schedulers. Why no ReiserFS? Google'd this (q: reiserfs ext2 cpu): 1 Apr 2006 ... Surprisingly, the ReiserFS and the XFS used significantly more CPU to remove file tree (86% and 65%) when other FS used about 15% (Ext3 and ... Is it same now?

    Read the article

  • mysql server overloading without error

    - by beny
    Hi, I have a serious problem on my server with MySQL server, it overload itself without any error in /var/log/mysqld What steps should I do to find out the problem ? my.cnf is [mysqld] set-variable=local-infile=0 datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql old_passwords=1 skip-bdb set-variable = innodb_buffer_pool_size=256M set-variable = innodb_additional_mem_pool_size=20M set-variable = innodb_log_file_size=128M set-variable = innodb_log_buffer_size=8M innodb_data_file_path = ibdata1:1000M:autoextend Please help, thx

    Read the article

  • c++ specialized overload?

    - by acidzombie24
    -edit- i am trying to close the question. i solved the problem with boost::is_base_and_derived In my class i want to do two things. 1) Copy int, floats and other normal values 2) Copy structs that supply a special copy function (template T copyAs(); } the struct MUST NOT return int's unless i explicitly say ints. I do not want the programmer mistaking the mistake by doing int a = thatClass; -edit- someone mention classes dont return anything, i mean using the operator Type() overload. How do i create my copy operator in such a way i can copy both 1) ints, floats etc and the the struct restricted in the way i mention in 2). i tried doing template <class T2> T operator = (const T2& v); which would cover my ints, floats etc. But how would it differentiate from structs? so i wrote T operator = (const SomeGenericBase& v); The idea was the GenericBase would be unsed instead then i can do v.Whatever. But that backfires bc the functions i want wouldnt exist, unless i use virtual, but virtual templates dont exist. Also i would hate to use virtual I think the solution is to get rid of ints and have it convert to something that can do .as(). So i wrote something up but now i have the same problem, how does that differentiate ints and structs that have the .as() function template?

    Read the article

  • C++ type-checking at compile-time

    - by Masterofpsi
    Hi, all. I'm pretty new to C++, and I'm writing a small library (mostly for my own projects) in C++. In the process of designing a type hierarchy, I've run into the problem of defining the assignment operator. I've taken the basic approach that was eventually reached in this article, which is that for every class MyClass in a hierarchy derived from a class Base you define two assignment operators like so: class MyClass: public Base { public: MyClass& operator =(MyClass const& rhs); virtual MyClass& operator =(Base const& rhs); }; // automatically gets defined, so we make it call the virtual function below MyClass& MyClass::operator =(MyClass const& rhs); { return (*this = static_cast<Base const&>(rhs)); } MyClass& MyClass::operator =(Base const& rhs); { assert(typeid(rhs) == typeid(*this)); // assigning to different types is a logical error MyClass const& casted_rhs = dynamic_cast<MyClass const&>(rhs); try { // allocate new variables Base::operator =(rhs); } catch(...) { // delete the allocated variables throw; } // assign to member variables } The part I'm concerned with is the assertion for type equality. Since I'm writing a library, where assertions will presumably be compiled out of the final result, this has led me to go with a scheme that looks more like this: class MyClass: public Base { public: operator =(MyClass const& rhs); // etc virtual inline MyClass& operator =(Base const& rhs) { assert(typeid(rhs) == typeid(*this)); return this->set(static_cast<Base const&>(rhs)); } private: MyClass& set(Base const& rhs); // same basic thing }; But I've been wondering if I could check the types at compile-time. I looked into Boost.TypeTraits, and I came close by doing BOOST_MPL_ASSERT((boost::is_same<BOOST_TYPEOF(*this), BOOST_TYPEOF(rhs)>));, but since rhs is declared as a reference to the parent class and not the derived class, it choked. Now that I think about it, my reasoning seems silly -- I was hoping that since the function was inline, it would be able to check the actual parameters themselves, but of course the preprocessor always gets run before the compiler. But I was wondering if anyone knew of any other way I could enforce this kind of check at compile-time.

    Read the article

  • Overloading properties in C#

    - by end-user
    Ok, I know that property overloading is not supported in C# - most of the references explain it by citing the single-method-different-returntype problem. However, what about setters? I'd like to directly assign a value as either a string or object, but only return as a string. Like this: public string FieldIdList { get { return fieldIdList.ToString(); } set { fieldIdList = new FieldIdList(value); } } public FieldIdList FieldIdList { set { fieldIdList = value; } } private FieldIdList fieldIdList; Why wouldn't this be allowed? I've also seen that "properties" simply create getter/setter functions on compile. Would it be possible to create my own? Something like: public void set_FieldIdList(FieldIdList value) { fieldIdList = value; } That would do the same thing. Thoughts?

    Read the article

  • Overloading on return type ???

    - by Green Hyena
    scala> val shares = Map("Apple" -> 23, "MicroSoft" -> 50, "IBM" -> 17) shares: scala.collection.immutable.Map[java.lang.String,Int] = Map(Apple -> 23, MicroSoft -> 50, IBM -> 17) scala> val shareholders = shares map {_._1} shareholders: scala.collection.immutable.Iterable[java.lang.String] = List(Apple, MicroSoft, IBM) scala> val newShares = shares map {case(k, v) => (k, 1.5 * v)} newShares: scala.collection.immutable.Map[java.lang.String,Double] = Map(Apple -> 34.5, MicroSoft -> 75.0, IBM -> 25.5) From this example it seems like the map method is overloaded on return type. Overloading on return type is not possible right? Would somebody please explain what's going on here?

    Read the article

  • operator+ overload returning object causing memory leaks, C++

    - by lampshade
    The problem i think is with returing an object when i overload the + operator. I tried returning a reference to the object, but doing so does not fix the memory leak. I can comment out the two statements: dObj = dObj + dObj2; and cObj = cObj + cObj2; to free the program of memory leaks. Somehow, the problem is with returning an object after overloading the + operator. #include <iostream> #include <vld.h> using namespace std; class Animal { public : Animal() {}; virtual void eat() = 0 {}; virtual void walk() = 0 {}; }; class Dog : public Animal { public : Dog(const char * name, const char * gender, int age); Dog() : name(NULL), gender(NULL), age(0) {}; virtual ~Dog(); Dog operator+(const Dog &dObj); private : char * name; char * gender; int age; }; class MyClass { public : MyClass() : action(NULL) {}; void setInstance(Animal &newInstance); void doSomething(); private : Animal * action; }; Dog::Dog(const char * name, const char * gender, int age) : // allocating here, for data passed in ctor name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age) { if (name) { size_t length = strlen(name) +1; strcpy_s(this->name, length, name); } else name = NULL; if (gender) { size_t length = strlen(gender) +1; strcpy_s(this->gender, length, gender); } else gender = NULL; if (age) { this->age = age; } } Dog::~Dog() { delete name; delete gender; age = 0; } Dog Dog::operator+(const Dog &dObj) { Dog d; d.age = age + dObj.age; return d; } void MyClass::setInstance(Animal &newInstance) { action = &newInstance; } void MyClass::doSomething() { action->walk(); action->eat(); } int main() { MyClass mObj; Dog dObj("Scruffy", "Male", 4); // passing data into ctor Dog dObj2("Scooby", "Male", 6); mObj.setInstance(dObj); // set the instance specific to the object. mObj.doSomething(); // something happens based on which object is passed in dObj = dObj + dObj2; // invoke the operator+ return 0; }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >