Search Results

Search found 3956 results on 159 pages for 'constructor overloading'.

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

  • C++ stream as a parameter when overloading operator<<

    - by TheOm3ga
    I'm trying to write my own logging class and use it as a stream: logger L; L << "whatever" << std::endl; This is the code I started with: #include <iostream> using namespace std; class logger{ public: template <typename T> friend logger& operator <<(logger& log, const T& value); }; template <typename T> logger& operator <<(logger& log, T const & value) { // Here I'd output the values to a file and stdout, etc. cout << value; return log; } int main(int argc, char *argv[]) { logger L; L << "hello" << '\n' ; // This works L << "bye" << "alo" << endl; // This doesn't work return 0; } But I was getting an error when trying to compile, saying that there was no definition for operator<<: pruebaLog.cpp:31: error: no match for ‘operator<<’ in ‘operator<< [with T = char [4]](((logger&)((logger*)operator<< [with T = char [4]](((logger&)(& L)), ((const char (&)[4])"bye")))), ((const char (&)[4])"alo")) << std::endl’ So, I've been trying to overload operator<< to accept this kind of streams, but it's driving me mad. I don't know how to do it. I've been loking at, for instance, the definition of std::endl at the ostream header file and written a function with this header: logger& operator <<(logger& log, const basic_ostream<char,char_traits<char> >& (*s)(basic_ostream<char,char_traits<char> >&)) But no luck. I've tried the same using templates instead of directly using char, and also tried simply using "const ostream& os", and nothing. Another thing that bugs me is that, in the error output, the first argument for operator<< changes, sometimes it's a reference to a pointer, sometimes looks like a double reference...

    Read the article

  • Method overloading in groovy

    - by slojo
    I am trying to take advantage of the convenience of groovy's scripting syntax to assign properties, but having trouble with a specific case. I must be missing something simple here. I define class A, B, C as so: class A { A() { println "Constructed class A!" } } class B { B() { println "Constructed class B!" } } class C { private member C() { println "Constructed class C!" } def setMember(A a) { println "Called setMember(A)!" member = a } def setMember(B b) { println "Called setMember(B)!" member = b } } And then try the following calls in a script: c = new C() c.setMember(new A()) // works c.member = new A() // works c.setMember(new B()) // works c.member = new B() // doesn't work! The last assignment results in an error: 'Cannot cast object of class B to class A". Why doesn't it call the proper setMember method for class B like it does for class A?

    Read the article

  • operator overloading and inheritance

    - by user168715
    I was given the following code: class FibHeapNode { //... // These all have trivial implementation virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); }; class Event : public FibHeapNode { // These have nontrivial implementation virtual void operator=(FibHeapNode& RHS); virtual int operator==(FibHeapNode& RHS); virtual int operator<(FibHeapNode& RHS); }; class FibHeap { //... int DecreaseKey(FibHeapNode *theNode, FibHeapNode& NewKey) { FibHeapNode *theParent; // Some code if (theParent != NULL && *theNode < *theParent) { //... } //... return 1; } }; Much of FibHeap's implementation is similar: FibHeapNode pointers are dereferenced and then compared. Why does this code work? (or is it buggy?) I would think that the virtuals here would have no effect: since *theNode and *theParent aren't pointer or reference types, no dynamic dispatch occurs and FibHeapNode::operator< gets called no matter what's written in Event.

    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

  • Overloading with same parameter signature

    - by Soham
    In C#, is it possible to have same parameters yet override each other(they are different in the return types) public override Stocks[] Search(string Field,string Param){ //some code} public override Stocks Search(string Field, string Param){//some code} C# returns compilation error

    Read the article

  • C++, overloading std::swap, compiler error, VS 2010

    - by Ian
    I would like to overload std::swap in my template class. In the following code (simplified) #ifndef Point2D_H #define Point2D_H template <class T> class Point2D { protected: T x; T y; public: Point2D () : x ( 0 ), y ( 0 ) {} Point2D( const T &x_, const T &y_ ) : x ( x_ ), y ( y_ ) {} .... public: void swap ( Point2D <T> &p ); }; template <class T> inline void swap ( Point2D <T> &p1, Point2D <T> &p2 ) { p1.swap ( p2 ); } namespace std { template <class T> inline void swap ( Point2D <T> &p1, Point2D <T> &p2 ) { p1.swap ( p2 ); } } template <class T> void Point2D <T>::swap ( Point2D <T> &p ) { using (std::swap); swap ( x, p.x ); swap ( y, p.y ); } #endif there is a compiler error (only in VS 2010): error C2668: 'std::swap' : ambiguous call to overloaded I do not know why, std::swap should be overoaded... Using g ++ code works perfectly. Without templates (i.e. Point2D is not a template class) this code also works.. Thanks for your help.

    Read the article

  • C# overloading with generics: bug or feature?

    - by TN
    Let's have a following simplified example: void Foo<T>(IEnumerable<T> collection, params T[] items) { // ... } void Foo<C, T>(C collection, T item) where C : ICollection<T> { // ... } void Main() { Foo((IEnumerable<int>)new[] { 1 }, 2); } Compiler says: The type 'System.Collections.Generic.IEnumerable' cannot be used as type parameter 'C' in the generic type or method 'UserQuery.Foo(C, T)'. There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'. If I change Main to: void Main() { Foo<int>((IEnumerable<int>)new[] { 1 }, 2); } It will work ok. Why compiler does not choose the right overload?

    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

  • Pair equal operator overloading for inserting into set

    - by Petwoip
    I am trying to add a pair<int,int> to a set. If a pair shares the same two values as another in the set, it should not be inserted. Here's my non-working code: typedef std::pair<int, int> PairInt; template<> bool std::operator==(const PairInt& l, const PairInt& r) { return (l.first == r.first && l.second == r.second) || (l.first == r.second && l.second == r.first); } int main() { std::set<PairInt> intSet; intSet.insert(PairInt(1,3)); intSet.insert(PairInt(1,4)); intSet.insert(PairInt(1,4)); intSet.insert(PairInt(4,1)); } At the moment, the (4,1) pair gets added even though there is already a (1,4) pair. The final contents of the set are: (1 3) (1 4) (4 1) and I want it to be (1 3) (1 4) I've tried putting breakpoints in the overloaded method, but they never get reached. What have I done wrong?

    Read the article

  • Operator Overloading << in c++

    - by thlgood
    I'm a fresh man in C++. I write this simple program to practice Overlaoding. This is my code: #include <iostream> #include <string> using namespace std; class sex_t { private: char __sex__; public: sex_t(char sex_v = 'M'):__sex__(sex_v) { if (sex_v != 'M' && sex_v != 'F') { cerr << "Sex type error!" << sex_v << endl; __sex__ = 'M'; } } const ostream& operator << (const ostream& stream) { if (__sex__ == 'M') cout << "Male"; else cout << "Female"; return stream; } }; int main(int argc, char *argv[]) { sex_t me('M'); cout << me << endl; return 0; } When I compiler it, It print a lots of error message: The error message was in a mess. It's too hard for me to found useful message sex.cpp: ???‘int main(int, char**)’?: sex.cpp:32:10: ??: ‘operator<<’?‘std::cout << me’????? sex.cpp:32:10: ??: ???: /usr/include/c++/4.6/ostream:110:7: ??: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostre

    Read the article

  • Is Operator Overloading supported in C

    - by caramel23
    Today when I was reading about LCC(windows) compiler I find out it has the implemention for operator overloading . I'm puzzled because after a bit of googling , it has been confirm that operator overloading ain't support in standard C , but I read some people's comment mentioning LCC is ANSI-compliant . So my real question is , is LCC really standard C or it's just like objective-c , a C variant with object-oriented feature ?

    Read the article

  • why Cannot invoke super constructor from enum constructor ?

    - by hilal
    public enum A { A(1); private A(int i){ } private A(){ super(); // compile - error // Cannot invoke super constructor from enum constructor A() } } and here is the hierarchy of enum A extends from abstract java.lang.Enum extends java.lang.Object Class c = Class.forName("/*path*/.A"); System.out.println(c.getSuperclass().getName()); System.out.println(Modifier.toString(c.getSuperclass().getModifiers()).contains("abstract")); System.out.println(c.getSuperclass().getSuperclass().getName());

    Read the article

  • Simple Constructor With Initializer List? - C++

    - by Alex
    Hi all, below I've included my h file, and my problem is that the compiler is not liking my simple exception class's constructor's with initializer lists. It also is saying that string is undeclared identifier, even though I have #include <string> at the top of the h file. Do you see something I am doing wrong? For further explanation, this is one of my domain classes that I'm integrating into a wxWidgets GUI application on Windows. Thanks! Time.h #pragma once #include <string> #include <iostream> // global constants for use in calculation const int HOURS_TO_MINUTES = 60; const int MINUTES_TO_HOURS = 100; class Time { public: // default Time class constructor // initializes all vars to default values Time(void); // ComputeEndTime computes the new delivery end time // params - none // preconditions - vars will be error-free // postconditions - the correct end time will be returned as an int // returns an int int ComputeEndTime(); // GetStartTime is the getter for var startTime // params - none // returns an int int GetStartTime() { return startTime; } // GetEndTime is the getter for var endTime // params - none // returns an int int GetEndTime() { return endTime; } // GetTimeDiff is the getter for var timeDifference // params - none // returns a double double GetTimeDiff() { return timeDifference; } // SetStartTime is the setter for var startTime // params - an int // returns void void SetStartTime(int s) { startTime = s; } // SetEndTime is the setter for var endTime // params - an int // returns void void SetEndTime(int e) { endTime = e; } // SetTimeDiff is the setter for var timeDifference // params - a double // returns void void SetTimeDiff(double t) { timeDifference = t; } // destructor for Time class ~Time(void); private: int startTime; int endTime; double timeDifference; }; class HourOutOfRangeException { public: // param constructor // initializes message to passed paramater // preconditions - param will be a string // postconditions - message will be initialized // params a string // no return type HourOutOfRangeException(string pMessage) : message(pMessage) {} // GetMessage is getter for var message // params none // preconditions - none // postconditions - none // returns string string GetMessage() { return message; } // destructor ~HourOutOfRangeException() {} private: string message; }; class MinuteOutOfRangeException { public: // param constructor // initializes message to passed paramater // preconditions - param will be a string // postconditions - message will be initialized // params a string // no return type MinuteOutOfRangeException(string pMessage) : message(pMessage) {} // GetMessage is getter for var message // params none // preconditions - none // postconditions - none // returns string string GetMessage() { return message; } // destructor ~MinuteOutOfRangeException() {} private: string message; }; class PercentageOutOfRangeException { public: // param constructor // initializes message to passed paramater // preconditions - param will be a string // postconditions - message will be initialized // params a string // no return type PercentageOutOfRangeException(string pMessage) : message(pMessage) {} // GetMessage is getter for var message // params none // preconditions - none // postconditions - none // returns string string GetMessage() { return message; } // destructor ~PercentageOutOfRangeException() {} private: string message; }; class StartEndException { public: // param constructor // initializes message to passed paramater // preconditions - param will be a string // postconditions - message will be initialized // params a string // no return type StartEndException(string pMessage) : message(pMessage) {} // GetMessage is getter for var message // params none // preconditions - none // postconditions - none // returns string string GetMessage() { return message; } // destructor ~StartEndException() {} private: string message; };

    Read the article

  • Passing array into constructor to use on JList

    - by OVERTONE
    I know the title sound confusing and thats because it is. its a bit long so try too stay with me. this is the layout i have my code designed variables constructor methods. im trying too fill a Jlist full on names. i want too get those names using a method. so here goes. in my variables i have my JList. its called contactNames; i also have an array which stores 5 strings which are the contacts names; heres the code for that anyway String contact1; String contact2; String contact3; String contact4; String contact5; String[] contactListNames; JList contactList; simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array fillContactList(); JList contactList = new JList(contactListNames); that method fillContactList() is coming up shortly. notice i dont have the array defined in the constructor. so heres my first question. can i do that? define the array to contain something in te constructor rather than filling it fromt the array. now heres where stuff gets balls up. ive created three different methods all of which havent worked. basically im trying to fill the array with all of them. this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time public void fillContactList() { for(int i = 0;i<3;i++) { try { String contact; System.out.println(" please fill the list at index "+ i); Scanner in = new Scanner(System.in); contact = in.next(); contactListNames[i] = contact; in.nextLine(); } catch(Exception e) { e.printStackTrace(); } } } unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at contactListNames[i] = contact; so my two questions in short are how i define an array in a constructor. and why cant i fill the array from that method. ************************888 **************************888 stack trace by request please fill the list at index 0 overtone java.lang.NullPointerException please fill the list at index 1 at project.AdminMessages.fillContactList(AdminMessages.java:408) at project.AdminMessages.<init>(AdminMessages.java:88) at project.AdminUser.createAdminMessages(AdminUser.java:32) at project.AdminUser.<init>(AdminUser.java:18) at project.AdminUser.main(AdminUser.java:47) it was a null poiinter exception

    Read the article

  • Conversion constructor vs. conversion operator: precedence

    - by GRB
    Reading some questions here on SO about conversion operators and constructors got me thinking about the interaction between them, namely when there is an 'ambiguous' call. Consider the following code: class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B's conversion constructor" << endl; } }; class A { public: operator B() //conversion operator { cout << "called A's conversion operator" << endl; return B(); } }; int main() { B b = A(); //what should be called here? apparently, A::operator B() return 0; } The above code displays "called A's conversion operator", meaning that the conversion operator is called as opposed to the constructor. If you remove/comment out the operator B() code from A, the compiler will happily switch over to using the constructor instead (with no other changes to the code). My questions are: Since the compiler doesn't consider B b = A(); to be an ambiguous call, there must be some type of precedence at work here. Where exactly is this precedence established? (a reference/quote from the C++ standard would be appreciated) From an object-oriented philosophical standpoint, is this the way the code should behave? Who knows more about how an A object should become a B object, A or B? According to C++, the answer is A -- is there anything in object-oriented practice that suggests this should be the case? To me personally, it would make sense either way, so I'm interested to know how the choice was made. Thanks in advance

    Read the article

  • LINQtoSQL Custom Constructor off Partial Class?

    - by sah302
    Hi all, I read this question here: http://stackoverflow.com/questions/82409/is-there-a-way-to-override-the-empty-constructor-in-a-class-generated-by-linqtosq Typically my constructor would look like: public User(String username, String password, String email, DateTime birthday, Char gender) { this.Id = Guid.NewGuid(); this.DateCreated = this.DateModified = DateTime.Now; this.Username = username; this.Password = password; this.Email = email; this.Birthday = birthday; this.Gender = gender; } However, as read in that question, you want to use partial method OnCreated() instead to assign values and not overwrite the default constructor. Okay so I got this : partial void OnCreated() { this.Id = Guid.NewGuid(); this.DateCreated = this.DateModified = DateTime.Now; this.Username = username; this.Password = password; this.Email = email; this.Birthday = birthday; this.Gender = gender; } However, this gives me two errors: Partial Methods must be declared private. Partial Methods must have empty method bodies. Alright I change it to Private Sub OnCreated() to remove both of those errors. However I am still stuck with...how can I pass it values as I would with a normal custom constructor? Also I am doing this in VB (converted it since I know most know/prefer C#), so would that have an affect on this?

    Read the article

  • Constructor or Assignment Operator

    - by ju
    Can you help me is there definition in C++ standard that describes which one will be called constructor or assignment operator in this case: #include <iostream> using namespace std; class CTest { public: CTest() : m_nTest(0) { cout << "Default constructor" << endl; } CTest(int a) : m_nTest(a) { cout << "Int constructor" << endl; } CTest(const CTest& obj) { m_nTest = obj.m_nTest; cout << "Copy constructor" << endl; } CTest& operatorint rhs) { m_nTest = rhs; cout << "Assignment" << endl; return *this; } protected: int m_nTest; }; int _tmain(int argc, _TCHAR* argv[]) { CTest b = 5; return 0; } Or is it just a matter of compiler optimization?

    Read the article

  • Constructor being called again?

    - by Halo
    I have this constructor; public UmlDiagramEntity(ReportElement reportElement, int pageIndex, Controller controller) { super(reportElement.getX1(), reportElement.getY1(), reportElement.getX2(), reportElement.getY2()); setLayout(null); this.pageIndex = pageIndex; this.controller = controller; reportElements = reportElement.getInternalReportElements(); components = new ArrayList<AbstractEntity>(); changedComponentIndex = -1; PageListener p = new PageListener(); this.addMouseMotionListener(p); this.addMouseListener(p); setPage(); } And I have an update method in the same class; @Override public void update(ReportElement reportElement) { if (changedComponentIndex == -1) { super.update(reportElement); } else { reportElements = reportElement.getInternalReportElements(); if (components.size() == reportElements.size()) { if (!isCommitted) { if (reportElement.getType() == ReportElementType.UmlRelation) { if (checkInvolvementAndSet(changedComponentIndex)) { anchorEntity(changedComponentIndex); } else { resistChanges(changedComponentIndex); } return; } } ..................goes on When I follow the flow from the debugger, I see that when update is called, somewhere in the method, the program goes into the constructor and executes it all over again (super, pageIndex, etc.). Why does it go to the constructor :D I didn't tell it to go there. I can make a deeper analysis and see where it goes to the constructor if you want. By the way, changedComponentIndex is a static variable.

    Read the article

  • Java Constructor Style (Check parameters aren't null)

    - by Peter
    What are the best practices if you have a class which accepts some parameters but none of them are allowed to be null? The following is obvious but the exception is a little unspecific: public class SomeClass { public SomeClass(Object one, Object two) { if (one == null || two == null) { throw new IllegalArgumentException("Parameters can't be null"); } //... } } Here the exceptions let you know which parameter is null, but the constructor is now pretty ugly: public class SomeClass { public SomeClass(Object one, Object two) { if (one == null) { throw new IllegalArgumentException("one can't be null"); } if (two == null) { throw new IllegalArgumentException("two can't be null"); } //... } Here the constructor is neater, but now the constructor code isn't really in the constructor: public class SomeClass { public SomeClass(Object one, Object two) { setOne(one); setTwo(two); } public void setOne(Object one) { if (one == null) { throw new IllegalArgumentException("one can't be null"); } //... } public void setTwo(Object two) { if (two == null) { throw new IllegalArgumentException("two can't be null"); } //... } } Which of these styles is best? Or is there an alternative which is more widely accepted? Cheers, Pete

    Read the article

  • C++: Constructor/destructor unresolved when not inline?

    - by Anamon
    In a plugin-based C++ project, I have a TmpClass that is used to exchange data between the main application and the plugins. Therefore the respective TmpClass.h is included in the abstract plugin interface class that is included by the main application project, and implemented by each plugin. As the plugins work on STL vectors of TmpClass instances, there needs to be a default constructor and destructor for the TmpClass. I had declared these in TmpClass.h: class TmpClass { TmpClass(); ~TmpClass(); } and implemented them in TmpClass.cpp. TmpClass::~TmpClass() {} TmpClass::TmpClass() {} However, when compiling plugins this leads to the linker complaining about two unresolved externals - the default constructor and destructor of TmpClass as required by the std::vector<TmpClass> template instantiation - even though all other functions I declare in TmpClass.h and implement in TmpClass.cpp work. As soon as I remove the (empty) default constructor and destructor from the .cpp file and inline them into the class declaration in the .h file, the plugins compile and work. Why is it that the default constructor and destructor have to be inline for this code to compile? Why does it even maatter? (I'm using MSVC++8).

    Read the article

  • Calling base class constructor

    - by The Void
    In the program below, is the line Derived(double y): Base(), y_(y) correct/allowed? That is, does it follow ANSI rules? #include <iostream> class Base { public: Base(): x_(0) { std::cout << "Base default constructor called" << std::endl; } Base(int x): x_(x) { std::cout << "Base constructor called with x = " << x << std::endl; } void display() const { std::cout << x_ << std::endl; } protected: int x_; }; class Derived: public Base { public: Derived(): Base(1), y_(1.2) { std::cout << "Derived default constructor called" << std::endl; } Derived(double y): Base(), y_(y) { std::cout << "Derived constructor called with y = " << y << std::endl; } void display() const { std::cout << Base::x_ << ", " << y_ << std::endl; } private: double y_; }; int main() { Base b1; b1.display(); Derived d1; d1.display(); std::cout << std::endl; Base b2(-9); b2.display(); Derived d2(-8.7); d2.display(); return 0; }

    Read the article

  • Java: design problem with final-value and empty constructor

    - by HH
    $ javac InitInt.java InitInt.java:7: variable right might not have been initialized InitInt(){} ^ 1 error $ cat InitInt.java import java.util.*; import java.io.*; public class InitInt { private final int right; // Design Problem? // I feel the initialization problem is just due to bad style. InitInt(){} InitInt{ // Still the error, "may not be initialized" // How to initialise it? if(snippetBuilder.length()>(charwisePos+25)){ right=charwisePos+25; }else{ right=snippetBuilder.length()-1; } } public static void main(String[] args) { InitInt test = new InitInt(); System.out.println(test.getRight()); } public int getRight(){return right;} } Partial Solutions and Suggestions use "this" to access methods in the class, instead of creating empty constructor change final to non-final with final field value: initialize all final values in every constructor remove the empty constructor, keep your code simple and clean

    Read the article

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