Search Results

Search found 597 results on 24 pages for 'constructors'.

Page 19/24 | < Previous Page | 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Casting Type array to Generic array?

    - by George R
    The short version of the question - why can't I do this? I'm restricted to .NET 3.5. T[] genericArray; // Obviously T should be float! genericArray = new T[3]{ 1.0f, 2.0f, 0.0f }; // Can't do this either, why the hell not genericArray = new float[3]{ 1.0f, 2.0f, 0.0f }; Longer version - I'm working with the Unity engine here, although that's not important. What is - I'm trying to throw conversion between its fixed Vector2 (2 floats) and Vector3 (3 floats) and my generic Vector< class. I can't cast types directly to a generic array. using UnityEngine; public struct Vector { private readonly T[] _axes; #region Constructors public Vector(int axisCount) { this._axes = new T[axisCount]; } public Vector(T x, T y) { this._axes = new T[2] { x, y }; } public Vector(T x, T y, T z) { this._axes = new T[3]{x, y, z}; } public Vector(Vector2 vector2) { // This doesn't work this._axes = new T[2] { vector2.x, vector2.y }; } public Vector(Vector3 vector3) { // Nor does this this._axes = new T[3] { vector3.x, vector3.y, vector3.z }; } #endregion #region Properties public T this[int i] { get { return _axes[i]; } set { _axes[i] = value; } } public T X { get { return _axes[0];} set { _axes[0] = value; } } public T Y { get { return _axes[1]; } set { _axes[1] = value; } } public T Z { get { return this._axes.Length (Vector2 vector2) { Vector vector = new Vector(vector2); return vector; } public static explicit operator Vector(Vector3 vector3) { Vector vector = new Vector(vector3); return vector; } #endregion }

    Read the article

  • Constructor and Destructors in C++ work?

    - by Jack
    I am using gcc. Please tell me if I am wrong - Lets say I have two classes A & B class A { public: A(){cout<<"A constructor"<<endl;} ~A(){cout<<"A destructor"<<endl;} }; class B:public A { public: B(){cout<<"B constructor"<<endl;} ~B(){cout<<"B destructor"<<endl;} }; 1) The first line in B's constructor should be a call to A's constructor ( I assume compiler automatically inserts it). Also the last line in B's destructor will be a call to A's destructor (compiler does it again). Why was it built this way? 2) When I say A * a = new B(); compiler creates a new B object and checks to see if A is a base class of B and if it is it allows 'a' to point to the newly created object. I guess that is why we don't need any virtual constructors. ( with help from @Tyler McHenry , @Konrad Rudolph) 3) When I write delete a compiler sees that a is an object of type A so it calls A's destructor leading to a problem which is solved by making A's destructor virtual. As user - Little Bobby Tables pointed out to me all destructors have the same name destroy() in memory so we can implement virtual destructors and now the call is made to B's destructor and all is well in C++ land. Please comment.

    Read the article

  • Constructor Overload Problem in C++ Inherrentance

    - by metdos
    Here my code snippet: class Request { public: Request(void); ……….. } Request::Request(void) { qDebug()<<"Request: "<<"Hello World"; } class LoginRequest :public Request { public: LoginRequest(void); LoginRequest(QDomDocument); …………… } LoginRequest::LoginRequest(void) { qDebug()<<"LoginRequest: "<<"Hello World"; requestType=LOGIN; requestId=-1; } LoginRequest::LoginRequest(QDomDocument doc){ qDebug()<<"LoginRequest: "<<"Hello World with QDomDocument"; LoginRequest::LoginRequest(); xmlDoc_=doc; } When call constructor of Overrided LoginRequest LoginRequest *test=new LoginRequest(doc); I came up with this result: Request: Hello World LoginRequest: Hello World with QDomDocument Request: Hello World LoginRequest: Hello World Obviously both constructor of LoginRequest called REquest constructor. Is there any way to cape with this situation? I can construct another function that does the job I want to do and have both constructors call that function. But I wonder is there any solution?

    Read the article

  • Variable length argument list - How to understand we retrieved the last argument?

    - by hkBattousai
    I have a Polynomial class which holds coefficients of a given polynomial. One of its overloaded constructors is supposed to receive these coefficients via variable argument list. template <class T> Polynomial<T>::Polynomial(T FirstCoefficient, ...) { va_list ArgumentPointer; va_start(ArgumentPointer, FirstCoefficient); T NextCoefficient = FirstCoefficient; std::vector<T> Coefficients; while (true) { Coefficients.push_back(NextCoefficient); NextCoefficient = va_arg(ArgumentPointer, T); if (/* did we retrieve all the arguments */) // How do I implement this? { break; } } m_Coefficients = Coefficients; } I know that we usually pass an extra parameter which tells the recipient method the total number of parameters, or we pass a sentimental ending parameter. But in order to keep thing short and clean, I don't prefer passing an extra parameter. Is there any way of doing this without modifying the method signature in the example?

    Read the article

  • useer degined Copy ctor, and copy-ctors further down the chain - compiler bug ? programers brainbug

    - by J.Colmsee
    Hi. i have a little problem, and I am not sure if it's a compiler bug, or stupidity on my side. I have this struct : struct BulletFXData { int time_next_fx_counter; int next_fx_steps; Particle particles[2];//this is the interesting one ParticleManager::ParticleId particle_id[2]; }; The member "Particle particles[2]" has a self-made kind of smart-ptr in it (resource-counted texture-class). this smart-pointer has a default constructor, that initializes to the ptr to 0 (but that is not important) I also have another struct, containing the BulletFXData struct : struct BulletFX { BulletFXData data; BulletFXRenderFunPtr render_fun_ptr; BulletFXUpdateFunPtr update_fun_ptr; BulletFXExplosionFunPtr explode_fun_ptr; BulletFXLifetimeOverFunPtr lifetime_over_fun_ptr; BulletFX( BulletFXData data, BulletFXRenderFunPtr render_fun_ptr, BulletFXUpdateFunPtr update_fun_ptr, BulletFXExplosionFunPtr explode_fun_ptr, BulletFXLifetimeOverFunPtr lifetime_over_fun_ptr) :data(data), render_fun_ptr(render_fun_ptr), update_fun_ptr(update_fun_ptr), explode_fun_ptr(explode_fun_ptr), lifetime_over_fun_ptr(lifetime_over_fun_ptr) { } /* //USER DEFINED copy-ctor. if it's defined things go crazy BulletFX(const BulletFX& rhs) :data(data),//this line of code seems to do a plain memory-copy without calling the right ctors render_fun_ptr(render_fun_ptr), update_fun_ptr(update_fun_ptr), explode_fun_ptr(explode_fun_ptr), lifetime_over_fun_ptr(lifetime_over_fun_ptr) { } */ }; If i use the user-defined copy-ctor my smart-pointer class goes crazy, and it seems that calling the CopyCtor / assignment operator aren't called as they should. So - does this all make sense ? it seems as if my own copy-ctor of struct BulletFX should do exactly what the compiler-generated would, but it seems to forget to call the right constructors down the chain. compiler bug ? me being stupid ? Sorry about the big code, some small example could have illustrated too. but often you guys ask for the real code, so well - here it is :D

    Read the article

  • Vector does reallocation on every push_back

    - by Amrish
    IDE - Visual Studio 2008, Visual C++ I have a custom class Class1 with a copy constructor to it. I also have a vector Data is inserted using the following code Class1* objClass1; vector<Class1> vClass1; for(int i=0;i<1000;i++) { objClass1 = new Class1(); vClass1.push_back(*objClass1); delete objClass1; } Now on every insert, the vector gets re-allocated and all the existing contents are copied to new locations. For example, if the vector has 5 elements and if I insert the 6th one, the previous 5 elements along with the new one gets copied to a new location (I figured it out by adding log statements in the copy constructors.) On using reserve(), this however does not happen as expected! I have the following questions Is it mandatory to always use the reserve statement? Does vector does a reallocation every time I do a push_back; or does it happen because I am debugging?

    Read the article

  • How to efficiently implement a strategy pattern with spring ?

    - by Anth0
    I have a web application developped in J2EE 1.5 with Spring framework. Application contains "dashboards" which are simple pages where a bunch of information are regrouped and where user can modify some status. Managers want me to add a logging system in database for three of theses dashboards. Each dashboard has different information but the log should be traced by date and user's login. What I'd like to do is to implement the Strategy pattern kind of like this : interface DashboardLog { void createLog(String login, Date now); } // Implementation for one dashboard class PrintDashboardLog implements DashboardLog { Integer docId; String status; void createLog(String login, Date now){ // Some code } } class DashboardsManager { DashboardLog logger; String login; Date now; void createLog(){ logger.log(login,now); } } class UpdateDocAction{ DashboardsManager dbManager; void updateSomeField(){ // Some action // Now it's time to log dbManagers.setLogger = new PrintDashboardLog(docId, status); dbManagers.createLog(); } } Is it "correct" (good practice, performance, ...) to do it this way ? Is there a better way ? Note :I did not write basic stuff like constructors and getter/setter.

    Read the article

  • std::vector elements initializing

    - by Chameleon
    std::vector<int> v1(1000); std::vector<std::vector<int>> v2(1000); std::vector<std::vector<int>::const_iterator> v3(1000); How elements of these 3 vectors initialized? About int, I test it and I saw that all elements become 0. Is this standard? I believed that primitives remain undefined. I create a vector with 300000000 elements, give non-zero values, delete it and recreate it, to avoid OS memory clear for data safety. Elements of recreated vector were 0 too. What about iterator? Is there a initial value (0) for default constructor or initial value remains undefined? When I check this, iterators point to 0, but this can be OS When I create a special object to track constructors, I saw that for first object, vector run the default constructor and for all others it run the copy constructor. Is this standard? Is there a way to completely avoid initialization of elements? Or I must create my own vector? (Oh my God, I always say NOT ANOTHER VECTOR IMPLEMENTATION) I ask because I use ultra huge sparse matrices with parallel processing, so I cannot use push_back() and of course I don't want useless initialization, when later I will change the value.

    Read the article

  • How do I pass dependency to object with Castle Windsor and MS Test?

    - by Nick
    I am trying to use Castle Windsor with MS Test. The test class only seems to use the default constructor. How do I configure Castle to resolve the service in the constructor? Here is the Test Class' constructors: private readonly IWebBrowser _browser; public DepressionSummaryTests() { } public DepressionSummaryTests(IWebBrowser browser) { _browser = browser; } My component in the app config looks like so: <castle> <components> <component id="browser" service="ConversationSummary.IWebBrowser, ConversationSummary" type="ConversationSummary.Browser" /> </components> </castle> Here is my application container: public class ApplicationContainer : WindsorContainer { private static IWindsorContainer container; static ApplicationContainer() { container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); } private static IWindsorContainer Container { get { return container; } } public static IWebBrowser Browser { get { return (IWebBrowser) Container.Resolve("browser"); } } } MS test requires the default constructor. What am I missing? Thanks!

    Read the article

  • How to use interfaces in exception handling

    - by vikp
    Hi, I'm working on the exception handling layer for my application. I have read few articles on interfaces and generics. I have used inheritance before quite a lot and I'm comfortable with in that area. I have a very brief design that I'm going to implement: public interface IMyExceptionLogger { public void LogException(); // Helper methods for writing into files,db, xml } I'm slightly confused what I should be doing next. public class FooClass: IMyExceptionLogger { // Fields // Constructors } Should I implement LogException() method within FooClass? If yes, than I'm struggling to see how I'm better of using an interface instead of the concrete class... I have a variety of classes that will make a use of that interface, but I don't want to write an implementation of that interface within each class. In the same time If I implement an interface in one class, and then use that class in different layers of the application I will be still using concrete classes instead of interfaces, which is a bad OO design... I hope this makes sense. Any feedback and suggestions are welcome. Please notice that I'm not interested in using net4log or its competitors because I'm doing this to learn. Thank you Edit: Wrote some more code. So I will implement variety of loggers with this interface, i.e. DBExceptionLogger, CSVExceptionLogger, XMLExceptionLogger etc. Than I will still end up with concrete classes that I will have to use in different layers of my application.

    Read the article

  • Unit test approach for generic classes/methods

    - by Greg
    Hi, What's the recommended way to cover off unit testing of generic classes/methods? For example (referring to my example code below). Would it be a case of have 2 or 3 times the tests to cover testing the methods with a few different types of TKey, TNode classes? Or is just one class enough? public class TopologyBase<TKey, TNode, TRelationship> where TNode : NodeBase<TKey>, new() where TRelationship : RelationshipBase<TKey>, new() { // Properties public Dictionary<TKey, NodeBase<TKey>> Nodes { get; private set; } public List<RelationshipBase<TKey>> Relationships { get; private set; } // Constructors protected TopologyBase() { Nodes = new Dictionary<TKey, NodeBase<TKey>>(); Relationships = new List<RelationshipBase<TKey>>(); } // Methods public TNode CreateNode(TKey key) { var node = new TNode {Key = key}; Nodes.Add(node.Key, node); return node; } public void CreateRelationship(NodeBase<TKey> parent, NodeBase<TKey> child) { . . .

    Read the article

  • Hibernate saveOrUpdate fails when I execute it on empty table.

    - by Vladimir
    I'm try to insert or update db record with following code: Category category = new Category(); category.setName('catName'); category.setId(1L); categoryDao.saveOrUpdate(category); When there is a category with id=1 already in database everything works. But if there is no record with id=1 I got following exception: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1: Here is my Category class setters, getters and constructors ommited for clarity: @Entity public class Category { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @ManyToOne private Category parent; @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent") private List<Category> categories = new ArrayList<Category>(); } In the console I see this hibernate query: update Category set name=?, parent_id=? where id=? So looks like hibernates tryis to update record instead of inserting new. What am I doing wrong here?

    Read the article

  • How can I avoid encoding mixups of strings in a C/C++ API?

    - by Frerich Raabe
    I'm working on implementing different APIs in C and C++ and wondered what techniques are available for avoiding that clients get the encoding wrong when receiving strings from the framework or passing them back. For instance, imagine a simple plugin API in C++ which customers can implement to influence translations. It might feature a function like this: const char *getTranslatedWord( const char *englishWord ); Now, let's say that I'd like to enforce that all strings are passed as UTF-8. Of course I'd document this requirement, but I'd like the compiler to enforce the right encoding, maybe by using dedicated types. For instance, something like this: class Word { public: static Word fromUtf8( const char *data ) { return Word( data ); } const char *toUtf8() { return m_data; } private: Word( const char *data ) : m_data( data ) { } const char *m_data; }; I could now use this specialized type in the API: Word getTranslatedWord( const Word &englishWord ); Unfortunately, it's easy to make this very inefficient. The Word class lacks proper copy constructors, assignment operators etc.. and I'd like to avoid unnecessary copying of data as much as possible. Also, I see the danger that Word gets extended with more and more utility functions (like length or fromLatin1 or substr etc.) and I'd rather not write Yet Another String Class. I just want a little container which avoids accidental encoding mixups. I wonder whether anybody else has some experience with this and can share some useful techniques. EDIT: In my particular case, the API is used on Windows and Linux using MSVC 6 - MSVC 10 on Windows and gcc 3 & 4 on Linux.

    Read the article

  • Should constant contructor aguments be passed by reference or value?

    - by Mike
    When const values are passed to an object construct should they be passed by reference or value? If you pass by value and the arguments are immediately fed to initializes are two copies being made? Is this something that the compiler will automatically take care of. I have noticed that all textbook examples of constructors and intitializers pass by value but this seems inefficient to me. class Point { public: int x; int y; Point(const int _x, const int _y) : x(_x), y(_y) {} }; int main() { const int a = 1, b = 2; Point p(a,b); Point q(3,5); cout << p.x << "," << p.y << endl; cout << q.x << "," << q.y << endl; } vs. class Point { public: int x; int y; Point(const int& _x, const int& _y) : x(_x), y(_y) {} }; Both compile and do the same thing but which is correct?

    Read the article

  • How to throw meaningful data in exceptions ?

    - by ZeroCool
    I would like to throw exceptions with meaningful explanation ! I thought of using variable arguments worked fine but lately I figured out it's impossible to extend the class in order to implement other exception types. So I figured out using an std::ostreamstring as a an internal buffer to deal with formatting ... but doesn't compile! I guess it has something to deal with copy constructors. Anyhow here is my piece of code: class Exception: public std::exception { public: Exception(const char *fmt, ...); Exception(const char *fname, const char *funcname, int line, const char *fmt, ...); //std::ostringstream &Get() { return os_ ; } ~Exception() throw(); virtual const char *what() const throw(); protected: char err_msg_[ERRBUFSIZ]; //std::ostringstream os_; }; The variable argumens constructor can't be inherited from! this is why I thought of std::ostringstream! Any advice on how to implement such approach ?

    Read the article

  • creating new instance fails PHP

    - by as3isolib
    I am relatively new to PHP and having some decent success however I am running into this issue: If I try to create a new instance of the class GenericEntryVO, I get a 500 error with little to no helpful error information. However, if I use a generic object as the result, I get no errors. I'd like to be able to cast this object as a GenericEntryVO as I am using AMFPHP to communicate serialize data with a Flex client. I've read a few different ways to create constructors in PHP but the typical 'public function Foo()' for a class Foo was recommended for PHP 5.4.4 //in my EntryService.php class public function getEntryByID($id) { $link = mysqli_connect("localhost", "root", "root", "BabyTrackingAppDB"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT * FROM Entries WHERE id = '$id' LIMIT 1"; if ($result = mysqli_query($link, $query)) { // $entry = new GenericEntryVO(); this is where the problem lies! while ($row = mysqli_fetch_row($result)) { $entry->id = $row[0]; $entry->entryType = $row[1]; $entry->title = $row[2]; $entry->description = $row[3]; $entry->value = $row[4]; $entry->created = $row[5]; $entry->updated = $row[6]; } } mysqli_free_result($result); mysqli_close($link); return $entry; } //my GenericEntryVO.php class <?php class GenericEntryVO { public function __construct() { } public $id; public $title; public $entryType; public $description; public $value; public $created; public $updated; // public $properties; } ?>

    Read the article

  • creating an object within a function of a program

    - by user1066524
    could someone please tell me what I need to do in order to create an object in a function. I will try to explain by making up some sort of example... Let's say I have a program named TimeScheduler.cpp that implements the class Schedule.h (and I have the implementation in a separate file Schedule.cpp where we define the methods). In the declaration file we have declared two constructors Schedule(); //the default and Schedule(int, int, int);//accepts three arguments to get to the point--let's say in the main program file TimeScheduler.cpp we created our own functions in this program apart from the functions inherited from the class Schedule. so we have our prototypes listed at the top. /*prototypes*/ void makeSomeTime(); etc..... we have main(){ //etc etc... } we then define these program functions void makeSomeTime(){ //process } let's say that inside the function makeSomeTime(), we would like to create an array of Schedule objects like this Schedule ob[]={ summer(5,14, 49), fall(9,25,50) }; what do I have to do to the function makeSomeTime() in order for it to allow me to create this array of objects. The reason I ask is currently i'm having difficulty with my own program in that it WILL allow me to create this array of objects in main()....but NOT in a function like I just gave an example of. The strange thing is it will allow me to create a dynamic array of objects in the function..... like Schedule *ob = new Schedule[n+1]; ob[2]= Schedule(x,y,z); Why would it let me assign to a non-dynamic array in main(), but not let me do that in the function?

    Read the article

  • Building a structure/object in a place other than the constructor

    - by Vishal Naidu
    I have different types of objects representing the same business entity. UIObject, PowershellObject, DevCodeModelObject, WMIObject all are different representation to the same entity. So say if the entity is Animal then I have AnimalUIObject, AnimalPSObject, AnimalModelObject, AnimalWMIObject, etc. Now the implementations of AnimalUIObject, AnimalPSObject, AnimalModelObject are all in separate assemblies. Now my scenario is I want to verify the contents of business entity Animal irrespective of the assembly it came from. So I created a GenericAnimal class to represent the Animal entity. Now in GenericAnimal I added the following constructors: GenericAnimal(AnimalUIObject) GenericAnimal(AnimalPSObject) GenericAnimal(AnimalModelObject) Basically I made GenericAnimal depend on all the underlying assemblies so that while verifying I deal with this abstraction. Now the other approach to do this is have GenericAnimal with an empty constructor an allow these underlying assemblies to have a Transform() method which would build the GenericAnimal. Both approaches have some pros and cons: The 1st approach: Pros: All construction logic is in one place in one class GenericAnimal Cons: GenericAnimal class must be touched every-time there is a new representation form. The 2nd approach: Pros: construction responsibility is delegated to the underlying assembly. Cons: As construction logic is spread accross assemblies, tomorrow if I need to add a property X in GenericAnimal then I have to touch all the assemblies to change the Transform method. Which approach looks better ? or Which would you consider a lesser evil ? Is there any alternative way better than the above two ?

    Read the article

  • How can I compare the performance of log() and fp division in C++?

    - by Ventzi Zhechev
    Hi, I’m using a log-based class in C++ to store very small floating-point values (as the values otherwise go beyond the scope of double). As I’m performing a large number of multiplications, this has the added benefit of converting the multiplications to sums. However, at a certain point in my algorithm, I need to divide a standard double value by an integer value and than do a *= to a log-based value. I have overloaded the *= operator for my log-based class and the right-hand side value is first converted to a log-based value by running log() and than added to the left-hand side value. Thus the operations actually performed are floating-point division, log() and floating-point summation. My question whether it would be faster to first convert the denominator to a log-based value, which would replace the floating-point division with floating-point subtraction, yielding the following chain of operations: twice log(), floating-point subtraction, floating-point summation. In the end, this boils down to whether floating-point division is faster or slower than log(). I suspect that a common answer would be that this is compiler and architecture dependent, so I’ll say that I use gcc 4.2 from Apple on darwin 10.3.0. Still, I hope to get an answer with a general remark on the speed of these two operators and/or an idea on how to measure the difference myself, as there might be more going on here, e.g. executing the constructors that do the type conversion etc. Cheers!

    Read the article

  • Ways to make (relatively) safe assumptions about the type of concrete subclasses?

    - by Kylotan
    I have an interface (defined as a abstract base class) that looks like this: class AbstractInterface { public: bool IsRelatedTo(const AbstractInterface& other) const = 0; } And I have an implementation of this (constructors etc omitted): class ConcreteThing { public: bool IsRelatedTo(const AbstractInterface& other) const { return m_ImplObject.has_relationship_to(other.m_ImplObject); } private: ImplementationObject m_ImplObject; } The AbstractInterface forms an interface in Project A, and the ConcreteThing lives in Project B as an implementation of that interface. This is so that code in Project A can access data from Project B without having a direct dependency on it - Project B just has to implement the correct interface. Obviously the line in the body of the IsRelatedTo function cannot compile - that instance of ConcreteThing has an m_ImplObject member, but it can't assume that all AbstractInterfaces do, including the other argument. In my system, I can actually assume that all implementations of AbstractInterface are instances of ConcreteThing (or subclasses thereof), but I'd prefer not to be casting the object to the concrete type in order to get at the private member, or encoding that assumption in a way that will crash without a diagnostic later if this assumption ceases to hold true. I cannot modify ImplementationObject, but I can modify AbstractInterface and ConcreteThing. I also cannot use the standard RTTI mechanism for checking a type prior to casting, or use dynamic_cast for a similar purpose. I have a feeling that I might be able to overload IsRelatedTo with a ConcreteThing argument, but I'm not sure how to call it via the base IsRelatedTo(AbstractInterface) method. It wouldn't get called automatically as it's not a strict reimplementation of that method. Is there a pattern for doing what I want here, allowing me to implement the IsRelatedTo function via ImplementationObject::has_relationship_to(ImplementationObject), without risky casts? (Also, I couldn't think of a good question title - please change it if you have a better one.)

    Read the article

  • C++ Problem: Class Promotion using derived class

    - by Michael Fitzpatrick
    I have a class for Float32 that is derived from Float32_base class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); } The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's. Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

    Read the article

  • Adding functions to Java class libraries

    - by Eric
    I'm using a Java class library that is in many ways incomplete: there are many classes that I feel ought to have additional member functions built in. However, I am unsure of the best practice of adding these member functions. Lets call the insufficient base class A. class A { public A(/*long arbitrary arguments*/) { //... } public A(/*long even more arbitrary arguments*/) { //... } public int func() { return 1; } } Ideally, I would like to add a function to A. However, I can't do that. My choice is between: class B extends A { //Implement ALL of A's constructors here public int reallyUsefulFunction() { return func()+1; } } and class AddedFuncs { public int reallyUsefulFunction(A a) { return a.func()+1; } } The way I see it, they both have advantages and disadvantages. The first choice gives a cleaner syntax than the second, and is more logical, but has problems: Let's say I have a third class, C, within the class library. class C { public A func() { return new A(/*...*/); } } As I see it, there is no easy way of doing this: C c; int useful = c.func().reallyUsefulFunction(); as the type returned by C.func() is an A, not a B, and you can't down-cast. So what is the best way of adding a member function to a read-only library class?

    Read the article

  • Any workarounds for non-static member array initialization?

    - by TomiJ
    In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays? [Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before main. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.] E.g. I'd like to have something like this (but this one doesn't work): class OtherClass { private: int data; public: OtherClass(int i) : data(i) {}; // No default constructor! }; class Foo { private: OtherClass inst[3]; // Array size fixed and known ahead of time. public: Foo(...) : inst[0](0), inst[1](1), inst[2](2) {}; }; The only workaround I'm aware of is the non-array one: class Foo { private: OtherClass inst0; OtherClass inst1; OtherClass inst2; OtherClass *inst[3]; public: Foo(...) : inst0(0), inst1(1), inst2(2) { inst[0]=&inst0; inst[1]=&inst1; inst[2]=&inst2; }; }; Edit: It should be stressed that OtherClass has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of Foo will be created), using the heap is essentially verboten. I've updated the examples above to highlight the first point.

    Read the article

  • RegExpValidator never matches

    - by babyangel86
    Hi, I've got a class that's meant to validate input fields to make sure the value is always a decimal. I've tested the regex here: http://livedocs.adobe.com/flex/3/html/help.html?content=validators_7.html, and it looks like it does the right thing, but in my app, I can't seem to get it to match to a number format. Class Definition: public class DecimalValidator { //------------------------------- ATTRIBUTES public var isDecimalValidator:RegExpValidator; //------------------------------- CONSTRUCTORS public function DecimalValidator() { isDecimalValidator = new RegExpValidator(); isDecimalValidator.expression = "^-?(\d+\.\d*|\.\d+)$"; isDecimalValidator.flags = "g"; isDecimalValidator.required = true; isDecimalValidator.property = "text"; isDecimalValidator.triggerEvent = FocusEvent.FOCUS_OUT; isDecimalValidator.noMatchError = "Float Expected"; } } Setting the source here: public function registerDecimalInputValidator(inputBox:TextInput, valArr:Array):void { // Add Validators var dValidator:DecimalValidator = new DecimalValidator(); dValidator.isDecimalValidator.source = inputBox; dValidator.isDecimalValidator.trigger = inputBox; inputBox.restrict = "[0-9].\\.\\-"; inputBox.maxChars = 10; valArr.push(dValidator.isDecimalValidator); } And Calling it here: registerDecimalInputValidator(textInput, validatorArr); Where textInput is an input box created earlier. Clearly I'm missing something simple yet important, but I'm not entirely sure what! Any help would be much appreciated.

    Read the article

  • Determining an object's variable name dynamically?

    - by ZenBlender
    Let's say I have some objects: ArrayList<SomeObject> list = new ArrayList<SomeObject>(); SomeObject A = new SomeObject(); SomeObject B = new SomeObject(); SomeObject C = new SomeObject(); SomeObject D = new SomeObject(); These constructors automatically add each object to the ArrayList so I can iterate over them but still maintain the variable names for direct access: public SomeObject(){ // init stuff here list.add(this); } But then, let's say I want to output some debug info, and iterate through list and print out the NAME of each object? How can I do that? Essentially, when "SomeObject A = new SomeObject();" is executed, I want to use reflection (if possible) to determine that this variable's name is "A" (a String) and either store that in the object when the constructor executes, or determine it dynamically through reflection when referencing this object with the variable named "A". Does that make sense? How can I do this? Thanks!

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24  | Next Page >