Search Results

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

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

  • function overloading in C

    - by FL4SOF
    Is there any way to achieve function overloading in C? I am looking at simple functions to be overloaded like foo (int a) foo (char b) foo (float c , int d) I think there is no straight forward way, looking for workarounds if any?

    Read the article

  • Partial overriding in Java (or dynamic overriding while overloading)

    - by Lie Ryan
    If I have a parent-child that defines some method .foo() like this: class Parent { public void foo(Parent arg) { System.out.println("foo in Function"); } } class Child extends Parent { public void foo(Child arg) { System.out.println("foo in ChildFunction"); } } When I called them like this: Child f = new Child(); Parent g = f; f.foo(new Parent()); f.foo(new Child()); g.foo(new Parent()); g.foo(new Child()); the output is: foo in Parent foo in Child foo in Parent foo in Parent But, I want this output: foo in Parent foo in Child foo in Parent foo in Child I have a Child class that extends Parent class. In the Child class, I want to "partially override" the Parent's foo(), that is, if the argument arg's type is Child then Child's foo() is called instead of Parent's foo(). That works Ok when I called f.foo(...) as a Child; but if I refer to it from its Parent alias like in g.foo(...) then the Parent's foo(..) get called irrespective of the type of arg. As I understand it, what I'm expecting doesn't happen because method overloading in Java is early binding (i.e. resolved statically at compile time) while method overriding is late binding (i.e. resolved dynamically at compile time) and since I defined a function with a technically different argument type, I'm technically overloading the Parent's class definition with a distinct definition, not overriding it. But what I want to do is conceptually "partially overriding" when .foo()'s argument is a subclass of the parent's foo()'s argument. I know I can define a bucket override foo(Parent arg) in Child that checks whether arg's actual type is Parent or Child and pass it properly, but if I have twenty Child, that would be lots of duplication of type-unsafe code. In my actual code, Parent is an abstract class named "Function" that simply throws NotImplementedException(). The children includes "Polynomial", "Logarithmic", etc and .foo() includes things like Child.add(Child), Child.intersectionsWith(Child), etc. Not all combination of Child.foo(OtherChild) are solvable and in fact not even all Child.foo(Child) is solvable. So I'm best left with defining everything undefined (i.e. throwing NotImplementedException) then defines only those that can be defined. So the question is: Is there any way to override only part the parent's foo()? Or is there a better way to do what I want to do?

    Read the article

  • Function overloading by return type?

    - by dsimcha
    Why don't more mainstream statically typed languages support function/method overloading by return type? I can't think of any that do. It seems no less useful or reasonable than supporting overload by parameter type. How come it's so much less popular?

    Read the article

  • Java overloading and overriding

    - by Padmanabh
    We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time?

    Read the article

  • typedef and operator overloading in C

    - by jocapco
    Suppose I typedef an integer or integer array or any known type: typedef int int2 Then I overload operator * for int2 pairs, now if I initialize variables a and b as int. Then will my * between a and b be the overloaded * ? How do I achieve overloading an int and yet also use * for int the way they are. Should I create a new type?

    Read the article

  • User defined conversion operator as argument for printf

    - by BC
    I have a class that defined a user defined operator for a TCHAR*, like so CMyClass::operator const TCHAR*() const { // returns text as const TCHAR* } I want to be able to do something like CMyClass myClass; _tprintf(_T("%s"), myClass); or even _tprintf(_T("%s"), CMyClass(value)); But when trying, printf always prints (null) instead of the value. I have also tried a normal char* operator, as well variations with const etc. It only works correctly if I explicitly call the operator or do a cast, like _tprintf(_T("%s\n"), (const TCHAR*)myClass); _tprintf(_T("%s\n"), myClass.operator const TCHAR *()); However, I don't want to cast. How can this be achieved? Note, that a possibility is to create a function that has a parameter of const TCHAR*, so that it forcible calls the operator TCHAR*, but this I also don't want to implement.

    Read the article

  • Overloading the QDataStream << and >> operators for a user-defined type

    - by Alex Wood
    I have a an object I'd like to be able to read and write to/from a QDataStream. The header is as follows: class Compound { public: Compound(QString, QPixmap*, Ui::MainWindow*); void saveCurrentInfo(); void restoreSavedInfo(QGraphicsScene*); void setImage(QPixmap*); QString getName(); private: QString name, homeNotes, addNotes, expText; Ui::MainWindow *gui; QPixmap *image; struct NMRdata { QString hnmrText, cnmrText, hn_nmrText, hn_nmrNucl, notes; int hnmrFreqIndex, cnmrFreqIndex, hn_nmrFreqIndex, hnmrSolvIndex, cnmrSolvIndex, hn_nmrSolvIndex; }*nmr_data; struct IRdata { QString uvConc, lowResMethod, irText, uvText, lowResText, highResText, highResCalc, highResFnd, highResFrmla, notes; int irSolvIndex, uvSolvIndex; }*ir_data; struct PhysicalData { QString mpEdit, bpEdit, mpParensEdit, bpParensEdit, rfEdit, phyText, optAlpha, optConc, elemText, elemFrmla, notes; int phySolvIndex, optSolvIndex; }*physical_data; }; For all intensive purposes, the class just serves as an abstraction for a handful of QStrings and a QPixmap. Ideally, I would be able to write a QList to a QDataStream but I'm not exactly sure how to go about doing this. If operator overloading is a suitable solution, would writing code like friend QDataStream& operator << (QDataStream&,Compound) { ... } be a potential solution? I'm very open to suggestions! Please let me know if any further clarification is needed.

    Read the article

  • overloaded stream insertion operator with a vector

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

    Read the article

  • overloaded stream insetion operator with a vector

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

    Read the article

  • How to change the meaning of pointer access operator

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

    Read the article

  • bug with varargs and overloading?

    - by pstanton
    There seems to be a bug in the Java varargs implementation. Java can't distinguish the appropriate type when a method is overloaded with different types of vararg parameters. It gives me an error The method ... is ambiguous for the type ... Consider the following code: public class Test { public static void main(String[] args) throws Throwable { doit(new int[]{1, 2}); // <- no problem doit(new double[]{1.2, 2.2}); // <- no problem doit(1.2f, 2.2f); // <- no problem doit(1.2d, 2.2d); // <- no problem doit(1, 2); // <- The method doit(double[]) is ambiguous for the type Test } public static void doit(double... ds) { System.out.println("doubles"); } public static void doit(int... is) { System.out.println("ints"); } } the docs say: "Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called." however they don't mention this error, and it's not the programmers that are finding it difficult, it's the compiler. thoughts?

    Read the article

  • Constructor Overloading

    - by Mark Baker
    Normally when I want to create a class constructor that accepts different types of parameters, I'll use a kludgy overloading principle of not defining any args in the constructor definition: e.g. for an ECEF coordinate class constructor, I want it to accept either $x, $y and $z arguments, or to accept a single array argument containg x, y and z values, or to accept a single LatLong object I'd create a constructor looking something like: function __construct() { // Identify if any arguments have been passed to the constructor if (func_num_args() > 0) { $args = func_get_args(); // Identify the overload constructor required, based on the datatype of the first argument $argType = gettype($args[0]); switch($argType) { case 'array' : // Array of Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromArray'; break; case 'object' : // A LatLong object that needs converting to Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromLatLong'; break; default : // Individual Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromXYZ'; break; } // Call the appropriate overload constructor call_user_func_array(array($this,$overloadConstructor),$args); } } // function __construct() I'm looking at an alternative: to provide a straight constructor with $x, $y and $z as defined arguments, and to provide static methods of createECEFfromArray() and createECEFfromLatLong() that handle all the necessary extraction of x, y and z; then create a new ECEF object using the standard constructor, and return that Which option is cleaner from an OO purists perspective?

    Read the article

  • Member function overloading/template specialization issue

    - by Ferruccio
    I've been trying to call the overloaded table::scan_index(std::string, ...) member function without success. For the sake of clarity, I have stripped out all non-relevant code. I have a class called table which has an overloaded/templated member function named scan_index() in order to handle strings as a special case. class table : boost::noncopyable { public: template <typename T> void scan_index(T val, std::function<bool (uint recno, T val)> callback) { // code } void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code } }; Then there is a hitlist class which has a number of templated member functions which call table::scan_index(T, ...) class hitlist { public: template <typename T> void eq(uint fieldno, T value) { table* index_table = db.get_index_table(fieldno); // code index_table->scan_index<T>(value, [&](uint recno, T n)->bool { // code }); } }; And, finally, the code which kicks it all off: hitlist hl; // code hl.eq<std::string>(*fieldno, p1.to_string()); The problem is that instead of calling table::scan_index(std::string, ...), it calls the templated version. I have tried using both overloading (as shown above) and a specialized function template (below), but nothing seems to work. After staring at this code for a few hours, I feel like I'm missing something obvious. Any ideas? template <> void scan_index<std::string>(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code }

    Read the article

  • C++ [] array operator with multiple arguments?

    - by genesys
    Can I define in C++ an array operator that takes multiple arguments? I tried it like this: const T& operator[](const int i, const int j, const int k) const{ return m_cells[k*m_resSqr+j*m_res+i]; } T& operator[](const int i, const int j, const int k){ return m_cells[k*m_resSqr+j*m_res+i]; } But I'm getting this error: error C2804 binary operator '[' has too many parameters

    Read the article

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

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

    Read the article

  • signature output operator overload

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

    Read the article

  • C++ operator[] syntax.

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

    Read the article

  • does overload operator-> a compile time action?

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

    Read the article

  • overloading "<<" with a struct (no class) cout style

    - by monkeyking
    I have a struct that I'd like to output using either 'std::cout' or some other output stream. Is this possible without using classes? Thanks #include <iostream> #include <fstream> template <typename T> struct point{ T x; T y; }; template <typename T> std::ostream& dump(std::ostream &o,point<T> p) const{ o<<"x: " << p.x <<"\ty: " << p.y <<std::endl; } template<typename T> std::ostream& operator << (std::ostream &o,const point<T> &a){ return dump(o,a); } int main(){ point<double> p; p.x=0.1; p.y=0.3; dump(std::cout,p); std::cout << p ;//how? return 0; } I tried different syntax' but I cant seem to make it work.

    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

  • Why doesn't is operator take in consideration if the explicit operator is overriden when checking ty

    - by Galilyou
    Hey Guys, Consider this code sample: public class Human { public string Value { get; set;} } public class Car { public static explicit operator Human (Car c) { Human h = new Human(); h.Value = "Value from Car"; return h; } } public class Program { public static void Mani() { Car c = new Car(); Human h = (Human)c; Console.WriteLine("h.Value = {0}", h.Value); Console.WriteLine(c is Human); } } Up I provide a possibility of an explicit cast from Car to Human, though Car and Human hierarchically are not related! The above code simply means that "Car is convertible to human" However, if you run the snippet you will find the expression c is Human evaluates to false! I used to believe that the is operator is kinda expensive cause it attempts to do an actual cast that might result in an InvalidCastException. If the operator is trying to cast, then the cast should succeed as there's an operator logic that should perform the cast! What does "is" test? Does test a hierarchical "is-a" relationship? Does test whether a variable type is convertible to a type?

    Read the article

  • Overload dereference operator

    - by zilgo
    I'm trying to overload the dereference operator, but compiling the following code results in the error 'initializing' : cannot convert from 'X' to 'int': struct X { void f() {} int operator*() const { return 5; } }; int main() { X* x = new X; int t = *x; delete x; return -898; } What am I doing wrong?

    Read the article

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