Search Results

Search found 2498 results on 100 pages for 'unary operator'.

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

  • 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

  • Perl Hash Slice, Replication x Operator, and sub params

    - by user210757
    Ok, I understand perl hash slices, and the "x" operator in Perl, but can someone explain the following code example from here (slightly simplified)? sub test{ my %hash; @hash{@_} = (undef) x @_; } Example Call to sub: test('one', 'two', 'three'); This line is what throws me: @hash{@_} = (undef) x @_; It is creating a hash where the keys are the parameters to the sub and initializing to undef, so: %hash: 'one' = undef, 'two' = undef, 'three' = undef The rvalue of the x operator should be a number; how is it that @_ is interpreted as the length of the sub's parameter array? I would expect you'd at least have to do this: @hash{@_} = (undef) x length(@_);

    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

  • Disallow using comma operator

    - by RiaD
    I never use the comma operator. But sometimes, when I write some recursions, I make a stupid mistake: I forget the function name. That's why the last operand is returned, not the result of a recursion call. Simplified example: int binpow(int a,int b){ if(!b) return 1; if(b&1) return a*binpow(a,b-1); return (a*a,b/2); // comma operator } Is it possible get a compilation error instead of incorrect, hard to debug code?

    Read the article

  • why must you provide the keyword const in operator overloads

    - by numerical25
    Just curious on why a param has to be a const in operation overloading CVector& CVector::operator= (const CVector& param) { x=param.x; y=param.y; return *this; } couldn't you have easily done something like this ?? CVector& CVector::operator= (CVector& param) //no const { x=param.x; y=param.y; return *this; } Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???

    Read the article

  • StringBuilder/StringBuffer vs. "+" Operator

    - by matt.seil
    I'm reading "Better, Faster, Lighter Java" (by Bruce Tate and Justin Gehtland) and am familiar with the readability requirements in agile type teams, such as what Robert Martin discusses in his clean coding books. On the team I'm on now, I've been told explicitly not to use the "+" operator because it creates extra (and unnecessary) string objects during runtime. But this article: http://www.ibm.com/developerworks/java/library/j-jtp01274.html Written back in '04 talks about how object allocation is about 10 machine instructions. (essentially free) It also talks about how the GC also helps to reduce costs in this environment. What is the actual performance tradeoffs between using "+," "StringBuilder," or "StringBuffer?" (In my case it is StringBuffer only as we are limited to Java 1.4.2.) StringBuffer to me results in ugly, less readable code, as a couple of examples in Tate's book demonstrates. And StringBuffer is thread-synchronized which seems to have its own costs that outweigh the "danger" in using the "+" operator. Thoughts/Opinions?

    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

  • Operator + for matrices in C++

    - by cibercitizen1
    I suppose the naive implementation of a + operator for matrices (2D for instance) in C++ would be: class Matrix { Matrix operator+ (Matrix other) const { Matrix result; // fill result with *this.data plus other.data return result; } } so we could use it like Matrix a; Matrix b; Matrix c; c = a + b; Right? But if matrices are big this is not efficient as we are doing one not-necessary copy (return result). Therefore, If we wan't to be efficient we have to forget the clean call: c = a + b; Right? What would you suggest / prefer ? Thanks.

    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

  • boost::spirit::karma using the alternatives operator (|) with conditions

    - by Ingemar
    I'm trying to generate a string from my own class called Value using boost::spirit::karma, but i got stuck with this. I've tried to extract my problem into a simple example. I want to generate a String with karma from instances of the following class: class Value { public: enum ValueType { BoolType, NumericType }; Value(bool b) : type_(BoolType), value_(b) {} Value(const double d) : type_(NumericType), value_(d) {}; ValueType type() { return type_; } operator bool() { return boost::get<bool>(value_); } operator double() { return boost::get<double>(value_); } private: ValueType type_; boost::variant<bool, double> value_; }; Here you can see what I'm tying to do: int main() { using karma::bool_; using karma::double_; using karma::rule; using karma::eps; std::string generated; std::back_insert_iterator<std::string> sink(generated); rule<std::back_insert_iterator<std::string>, Value()> value_rule = bool_ | double_; Value bool_value = Value(true); Value double_value = Value(5.0); karma::generate(sink, value_rule, bool_value); std::cout << generated << "\n"; generated.clear(); karma::generate(sink, value_rule, double_value); std::cout << generated << "\n"; return 0; } The first call to karma::generate() works fine because the value is a bool and the first generator in my rule also "consumes" a bool. But the second karma::generate() fails with boost::bad_get because karma tries to eat a bool and calls therefore Value::operator bool(). My next thought was to modify my generator rule and use the eps() generator together with a condition but here i got stuck: value_rule = (eps( ... ) << bool_) | (eps( ... ) << double_); I'm unable to fill the brackets of the eps generator with sth. like this (of course not working): eps(value.type() == BoolType) I've tried to get into boost::phoenix, but my brain seems not to be ready for things like this. Please help me! here is my full example (compiling but not working): main.cpp

    Read the article

  • C++ conversion operator between types in other libraries

    - by Dave
    For convenience, I'd like to be able to cast between two types defined in other libraries. (Specifically, QString from the Qt library and UnicodeString from the ICU library.) Right now, I have created utility functions in a project namespace: namespace MyProject { const icu_44::UnicodeString ToUnicodeString(const QString& value); const QString ToQString(const icu_44::UnicodeString& value); } That's all well and good, but I'm wondering if there's a more elegant way. Ideally, I'd like to be able to convert between them using a cast operator. I do, however, want to retain the explicit nature of the conversion. An implicit conversion should not be possible. Is there a more elegant way to achieve this without modifying the source code of the libraries? Some operator overload syntax, perhaps?

    Read the article

  • Operator as and generic classes

    - by abatishchev
    I'm writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable: object Execute() { return type.InvokeMember(..); } T Execute<T>() { return Execute() as T; /* doesn't work: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint */ // also neither typeof(T) not T.GetType(), so on are possible return (T) Execute(); // ok } But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?

    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

  • Should I use parentheses in logical statements even where not necessary?

    - by Jeff Bridgman
    Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedent than OR. I could write this line of code: If (a AND b) OR (c AND d) Then ... But really, that's equivalent to: If a AND b OR c AND d Then ... Are there any arguments in for or against including the extraneous parentheses? Does practical experience suggest that it is worth including them for readability? Or is it a sign that a developer needs to really sit down and become confident in the basics of their language?

    Read the article

  • STL operator= behavior change with Visual Studio 2010?

    - by augnob
    Hi, I am attempting to compile QtScriptGenerator (gitorious) with Visual Studio 2010 (C++) and have run into a compile error. In searching for a solution, I have seen occasional references to compile breakages introduced since VS2008 due to changes in VS2010's implementation of STL and/or c++0x conformance changes. Any ideas what is happening below, or how I could go about fixing it? If the offending code appeared to be QtScriptGenerator's, I think I would have an easier time fixing it.. but it appears to me that the offending code may be in VS2010's STL implementation and I may be required to create a workaround? PS. I am pretty unfamiliar with templates and STL. I have a background in embedded and console projects where such things have until recently often been avoided to reduce memory consumption and cross-compiler risks. C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\xutility(275) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'rpp::pp_output_iterator<_Container>' (or there is no acceptable conversion) with [ _Container=std::string ] c:\qt\qtscriptgenerator\generator\parser\rpp\pp-iterator.h(75): could be 'rpp::pp_output_iterator<_Container> &rpp::pp_output_iterator<_Container>::operator =(const char &)' with [ _Container=std::string ] while trying to match the argument list '(rpp::pp_output_iterator<_Container>, rpp::pp_output_iterator<_Container>)' with [ _Container=std::string ] C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\xutility(2176) : see reference to function template instantiation '_Iter &std::_Rechecked<_OutIt,_OutIt>(_Iter &,_UIter)' being compiled with [ _Iter=rpp::pp_output_iterator<std::string>, _OutIt=rpp::pp_output_iterator<std::string>, _UIter=rpp::pp_output_iterator<std::string> ] c:\qt\qtscriptgenerator\generator\parser\rpp\pp-internal.h(83) : see reference to function template instantiation '_OutIt std::copy<std::_String_iterator<_Elem,_Traits,_Alloc>,_OutputIterator>(_InIt,_InIt,_OutIt)' being compiled with [ _OutIt=rpp::pp_output_iterator<std::string>, _Elem=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>, _OutputIterator=rpp::pp_output_iterator<std::string>, _InIt=std::_String_iterator<char,std::char_traits<char>,std::allocator<char>> ] c:\qt\qtscriptgenerator\generator\parser\rpp\pp-engine-bits.h(500) : see reference to function template instantiation 'void rpp::_PP_internal::output_line<_OutputIterator>(const std::string &,int,_OutputIterator)' being compiled with [ _OutputIterator=rpp::pp_output_iterator<std::string> ] C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\xutility(275) : error C2582: 'operator =' function is unavailable in 'rpp::pp_output_iterator<_Container>' with [ _Container=std::string ] Here's some context.. pp-internal.h-- #ifndef PP_INTERNAL_H #define PP_INTERNAL_H #include <algorithm> #include <stdio.h> namespace rpp { namespace _PP_internal { .. 68 template <typename _OutputIterator> 69 void output_line(const std::string &__filename, int __line, _OutputIterator __result) 70 { 71 std::string __msg; 72 73 __msg += "# "; 74 75 char __line_descr[16]; 76 pp_snprintf (__line_descr, 16, "%d", __line); 77 __msg += __line_descr; 78 79 __msg += " \""; 80 81 if (__filename.empty ()) 82 __msg += "<internal>"; 83 else 84 __msg += __filename; 85 86 __msg += "\"\n"; 87 std::copy (__msg.begin (), __msg.end (), __result); 88 }

    Read the article

  • vector does not erase content correctly (infite amount run of copy asignment operator untill crash [BEX])?

    - by Gam Erix
    Well my problem is that after I want to "unload" loaded DLL's the copy assignmnent operator is called an unlimited amount of times until crash. The code from which I remove the vector data looks like this: void UnloadPlugins() { dbg(("[DBG]UnloadPlugins()")); for(std::vector<DLLInfo>::iterator it = plugins.begin(); it != plugins.end(); ++it) { plugins.erase(it); } dbg(("[DBG]UnloadPlugins()::Done")); } however "[DBG]UnloadPlugins()::Done" gets never printed. this is my copy assignmnent operator: // 2. copy assignment operator DLLInfo& operator=(const DLLInfo& that) { dbg(("[DBG]Start-DLLInfo& operator=(const DLLInfo& that)")); Instance = that.Instance;//hinstance dbg(("[DBG]DLLInfo 1")); //Identifier.assign(that.Identifier);//string dbg(("[DBG]DLLInfo 2")); IsAMX = that.IsAMX;//integer dbg(("[DBG]DLLInfo 3")); dwSupportFlags = that.dwSupportFlags;//integer dbg(("[DBG]DLLInfo 4")); Load = that.Load;//integer dbg(("[DBG]DLLInfo 5")); Unload = that.Unload;//integer dbg(("[DBG]DLLInfo 6")); Supports = that.Supports;//integer dbg(("[DBG]DLLInfo 7")); ProcessTick = that.ProcessTick;//integer dbg(("[DBG]DLLInfo 8")); AmxLoad = that.AmxLoad;//integer dbg(("[DBG]DLLInfo 9")); AmxUnload = that.AmxUnload;//integer dbg(("[DBG]DLLInfo 10")); UseDestructor = that.UseDestructor;//bool dbg(("[DBG]DLLInfo 11")); KeyboardHit = that.KeyboardHit;//integer dbg(("[DBG]End-DLLInfo& operator=(const DLLInfo& that)")); return *this; } So the log looks like: [17:50:50] [DBG]UnloadPlugins() [17:50:50] [DBG]~DLLInfo [17:50:50] [DBG]~DLLInfo::if(this->UseDestructor) passed [17:50:50] [DBG]~DLLInfo::if(this->UseDestructor)::if(this->Unload != NULL && this->IsAMX) passed [17:50:50] [DBG]~DLLInfo::end [17:50:50] [DBG]Start-DLLInfo& operator=(const DLLInfo& that) [17:50:50] [DBG]DLLInfo 1 [17:50:50] [DBG]DLLInfo 2 [17:50:50] [DBG]DLLInfo 3 [17:50:50] [DBG]DLLInfo 4 [17:50:50] [DBG]DLLInfo 5 [17:50:50] [DBG]DLLInfo 6 [17:50:50] [DBG]DLLInfo 7 [17:50:50] [DBG]DLLInfo 8 [17:50:50] [DBG]DLLInfo 9 [17:50:50] [DBG]DLLInfo 10 [17:50:50] [DBG]DLLInfo 11 [17:50:50] [DBG]End-DLLInfo& operator=(const DLLInfo& that) [17:50:50] [DBG]Start-DLLInfo& operator=(const DLLInfo& that) ... [17:50:50] [DBG]End-DLLInfo& operator=(const DLLInfo& that) ...repeat until crash What could the problem be?

    Read the article

  • Entity Framework 4 Code First and the new() Operator

    - by Eric J.
    I have a rather deep hierarchy of objects that I'm trying to persist with Entity Framework 4, POCO, PI (Persistence Ignorance) and Code First. Suddenly things started working pretty well when it dawned on me to not use the new() operator. As originally written, the objects frequently use new() to create child objects. Instead I'm using my take on the Repository Pattern to create all child objects as needed. For example, given: class Adam { List<Child> children; void AddChildGivenInput(string input) { children.Add(new Child(...)); } } class Child { List<GrandChild> grandchildren; void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); } } class GrandChild { } ("GivenInput" implies some processing not shown here) I define an AdamRepository like: class AdamRepository { Adam Add() { return objectContext.Create<Adam>(); } Child AddChildGivenInput(Adam adam, string input) { return adam.children.Add(new Child(...)); } GrandChild AddGrandchildGivenInput(Child child, string input) { return child.grandchildren.Add(new GrandChild(...)); } } Now, this works well enough. However, I'm no longer "ignorant" of my persistence mechanism as I have abandoned the new() operator. Additionally, I'm at risk of an anemic domain model since so much logic ends up in the repository rather than in the domain objects. After much adieu, a question: Or rather several questions... Is this pattern required to work with EF 4 Code First? Is there a way to retain use of new() and still work with EF 4 / POCO / Code First? Is there another pattern that would leave logic in the domain object and still work with EF 4 / POCO / Code First? Will this restriction be lifted in later versions of Code First support? Sometimes trying to go the POCO / Persistence Ignorance route feels like swimming upstream, other times it feels like swimming up Niagra Falls.

    Read the article

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