Search Results

Search found 47245 results on 1890 pages for 'class members'.

Page 7/1890 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • C++ classes with members referencing each other

    - by Saad Imran.
    I'm trying to write 2 classes with members that reference each other. I'm not sure if I'm doing something wrong or it's just not possible. Can anyone help me out here... Source.cpp #include "Headers.h" using namespace std; void main() { Network* network = new Network(); system("pause"); return; } Headers.h #ifndef Headers_h #define Headers_h #include <iostream> #include <vector> #include "Network.h" #include "Router.h" #endif Network.h #include "Headers.h" class Network { protected: vector<Router> Routers; }; Router.h #include "Headers.h" class Router { protected: Network* network; public: }; The errors I'm getting are: error C2143: syntax error : missing ';' before '<' error C2238: unexpected token(s) preceding ';' error C4430: missing type specifier - int assumed. I'm pretty sure I'm not missing any semicolons or stuff like that. The program works find if I take out one of the members. I tried finding similar questions and the solution was to use pointers, but that's what I'm doing and it does't seem to be working!

    Read the article

  • Declare private static members in F#?

    - by acidzombie24
    I decided to port the class in C# below to F# as an exercise. It was difficult. I only notice three problems 1) Greet is visible 2) I can not get v to be a static class variable 3) I do not know how to set the greet member in the constructor. How do i fix these? The code should be similar enough that i do not need to change any C# source. ATM only Test1.v = 21; does not work C# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CsFsTest { class Program { static void Main(string[] args) { Test1.hi("stu"); new Test1().hi(); Test1.v = 21; var a = new Test1("Stan"); a.hi(); a.a = 9; Console.WriteLine("v = {0} {1} {2}", a.a, a.b, a.NotSTATIC()); } } class Test1 { public int a; public int b { get { return a * 2; } } string greet = "User"; public static int v; public Test1() {} public Test1(string name) { greet = name; } public static void hi(string greet) { Console.WriteLine("Hi {0}", greet); } public void hi() { Console.WriteLine("Hi {0} #{1}", greet, v); } public int NotSTATIC() { return v; } } } F# namespace CsFsTest type Test1 = (* public int a; public int b { get { return a * 2; } } string greet = "User"; public static int v; *) [<DefaultValue>] val mutable a : int member x.b = x.a * 2 member x.greet = "User" (*!! Needs to be private *) [<DefaultValue>] val mutable v : int (*!! Needs to be static *) (* public Test1() {} public Test1(string name) { greet = name; } *) new () = {} new (name) = { } (* public static void hi(string greet) { Console.WriteLine("Hi {0}", greet); } public void hi() { Console.WriteLine("Hi {0} #{1}", greet, v); } public int NotSTATIC() { return v; } *) static member hi(greet) = printfn "hi %s" greet member x.hi() = printfn "hi %s #%i" x.greet x.v member x.NotSTATIC() = x.v

    Read the article

  • Objective-C Class Question?

    - by tarnfeld
    Hey, My head is about to explode with this logic, can anyone help? Class A #imports Class B. Class A calls Method A in Class B. This works great Class B wants to send a response back to Class A from another method that is called from Method A. If you #import Class A from Class B, it is in effect an infinite loop and the whole thing crashes. Is there a way to do this properly, like a parent type thing? BTW, I'm developing for iPhone.

    Read the article

  • Followup: Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I asked a question at Python 2.6, 3 abstract base class misunderstanding. My problem was that python abstract base classes didn't work quite the way I expected them to. There was some discussion in the comments about why I would want to use ABCs at all, and Alex Martelli provided an excellent answer on why my use didn't work and how to accomplish what I wanted. Here I'd like to address why one might want to use ABCs, and show my test code implementation based on Alex's answer. tl;dr: Code after the 16th paragraph. In the discussion on the original post, statements were made along the lines that you don't need ABCs in Python, and that ABCs don't do anything and are therefore not real classes; they're merely interface definitions. An abstract base class is just a tool in your tool box. It's a design tool that's been around for many years, and a programming tool that is explicitly available in many programming languages. It can be implemented manually in languages that don't provide it. An ABC is always a real class, even when it doesn't do anything but define an interface, because specifying the interface is what an ABC does. If that was all an ABC could do, that would be enough reason to have it in your toolbox, but in Python and some other languages they can do more. The basic reason to use an ABC is when you have a number of classes that all do the same thing (have the same interface) but do it differently, and you want to guarantee that that complete interface is implemented in all objects. A user of your classes can rely on the interface being completely implemented in all classes. You can maintain this guarantee manually. Over time you may succeed. Or you might forget something. Before Python had ABCs you could guarantee it semi-manually, by throwing NotImplementedError in all the base class's interface methods; you must implement these methods in derived classes. This is only a partial solution, because you can still instantiate such a base class. A more complete solution is to use ABCs as provided in Python 2.6 and above. Template methods and other wrinkles and patterns are ideas whose implementation can be made easier with full-citizen ABCs. Another idea in the comments was that Python doesn't need ABCs (understood as a class that only defines an interface) because it has multiple inheritance. The implied reference there seems to be Java and its single inheritance. In Java you "get around" single inheritance by inheriting from one or more interfaces. Java uses the word "interface" in two ways. A "Java interface" is a class with method signatures but no implementations. The methods are the interface's "interface" in the more general, non-Java sense of the word. Yes, Python has multiple inheritance, so you don't need Java-like "interfaces" (ABCs) merely to provide sets of interface methods to a class. But that's not the only reason in software development to use ABCs. Most generally, you use an ABC to specify an interface (set of methods) that will likely be implemented differently in different derived classes, yet that all derived classes must have. Additionally, there may be no sensible default implementation for the base class to provide. Finally, even an ABC with almost no interface is still useful. We use something like it when we have multiple except clauses for a try. Many exceptions have exactly the same interface, with only two differences: the exception's string value, and the actual class of the exception. In many exception clauses we use nothing about the exception except its class to decide what to do; catching one type of exception we do one thing, and another except clause catching a different exception does another thing. According to the exception module's doc page, BaseException is not intended to be derived by any user defined exceptions. If ABCs had been a first class Python concept from the beginning, it's easy to imagine BaseException being specified as an ABC. But enough of that. Here's some 2.6 code that demonstrates how to use ABCs, and how to specify a list-like ABC. Examples are run in ipython, which I like much better than the python shell for day to day work; I only wish it was available for python3. Your basic 2.6 ABC: from abc import ABCMeta, abstractmethod class Super(): __metaclass__ = ABCMeta @abstractmethod def method1(self): pass Test it (in ipython, python shell would be similar): In [2]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 Notice the end of the last line, where the TypeError exception tells us that method1 has not been implemented ("abstract methods method1"). That was the method designated as @abstractmethod in the preceding code. Create a subclass that inherits Super, implement method1 in the subclass and you're done. My problem, which caused me to ask the original question, was how to specify an ABC that itself defines a list interface. My naive solution was to make an ABC as above, and in the inheritance parentheses say (list). My assumption was that the class would still be abstract (can't instantiate it), and would be a list. That was wrong; inheriting from list made the class concrete, despite the abstract bits in the class definition. Alex suggested inheriting from collections.MutableSequence, which is abstract (and so doesn't make the class concrete) and list-like. I used collections.Sequence, which is also abstract but has a shorter interface and so was quicker to implement. First, Super derived from Sequence, with nothing extra: from abc import abstractmethod from collections import Sequence class Super(Sequence): pass Test it: In [6]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods __getitem__, __len__ We can't instantiate it. A list-like full-citizen ABC; yea! Again, notice in the last line that TypeError tells us why we can't instantiate it: __getitem__ and __len__ are abstract methods. They come from collections.Sequence. But, I want a bunch of subclasses that all act like immutable lists (which collections.Sequence essentially is), and that have their own implementations of my added interface methods. In particular, I don't want to implement my own list code, Python already did that for me. So first, let's implement the missing Sequence methods, in terms of Python's list type, so that all subclasses act as lists (Sequences). First let's see the signatures of the missing abstract methods: In [12]: help(Sequence.__getitem__) Help on method __getitem__ in module _abcoll: __getitem__(self, index) unbound _abcoll.Sequence method (END) In [14]: help(Sequence.__len__) Help on method __len__ in module _abcoll: __len__(self) unbound _abcoll.Sequence method (END) __getitem__ takes an index, and __len__ takes nothing. And the implementation (so far) is: from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() Test it: In [34]: a = Super() In [35]: a Out[35]: [] In [36]: print a [] In [37]: len(a) Out[37]: 0 In [38]: a[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() /home/aaron/projects/test/test.py in __getitem__(self, index) 10 # Abstract method in Sequence, implemented in terms of list. 11 def __getitem__(self, index): ---> 12 return self._list.__getitem__(index) 13 14 # Abstract method in Sequence, implemented in terms of list. IndexError: list index out of range Just like a list. It's not abstract (for the moment) because we implemented both of Sequence's abstract methods. Now I want to add my bit of interface, which will be abstract in Super and therefore required to implement in any subclasses. And we'll cut to the chase and add subclasses that inherit from our ABC Super. from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() @abstractmethod def method1(): pass class Sub0(Super): pass class Sub1(Super): def __init__(self): self._list = [1, 2, 3] def method1(self): return [x**2 for x in self._list] def method2(self): return [x/2.0 for x in self._list] class Sub2(Super): def __init__(self): self._list = [10, 20, 30, 40] def method1(self): return [x+2 for x in self._list] We've added a new abstract method to Super, method1. This makes Super abstract again. A new class Sub0 which inherits from Super but does not implement method1, so it's also an ABC. Two new classes Sub1 and Sub2, which both inherit from Super. They both implement method1 from Super, so they're not abstract. Both implementations of method1 are different. Sub1 and Sub2 also both initialize themselves differently; in real life they might initialize themselves wildly differently. So you have two subclasses which both "is a" Super (they both implement Super's required interface) although their implementations are different. Also remember that Super, although an ABC, provides four non-abstract methods. So Super provides two things to subclasses: an implementation of collections.Sequence, and an additional abstract interface (the one abstract method) that subclasses must implement. Also, class Sub1 implements an additional method, method2, which is not part of Super's interface. Sub1 "is a" Super, but it also has additional capabilities. Test it: In [52]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 In [53]: a = Sub0() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Sub0 with abstract methods method1 In [54]: a = Sub1() In [55]: a Out[55]: [1, 2, 3] In [56]: b = Sub2() In [57]: b Out[57]: [10, 20, 30, 40] In [58]: print a, b [1, 2, 3] [10, 20, 30, 40] In [59]: a, b Out[59]: ([1, 2, 3], [10, 20, 30, 40]) In [60]: a.method1() Out[60]: [1, 4, 9] In [61]: b.method1() Out[61]: [12, 22, 32, 42] In [62]: a.method2() Out[62]: [0.5, 1.0, 1.5] [63]: a[:2] Out[63]: [1, 2] In [64]: a[0] = 5 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: 'Sub1' object does not support item assignment Super and Sub0 are abstract and can't be instantiated (lines 52 and 53). Sub1 and Sub2 are concrete and have an immutable Sequence interface (54 through 59). Sub1 and Sub2 are instantiated differently, and their method1 implementations are different (60, 61). Sub1 includes an additional method2, beyond what's required by Super (62). Any concrete Super acts like a list/Sequence (63). A collections.Sequence is immutable (64). Finally, a wart: In [65]: a._list Out[65]: [1, 2, 3] In [66]: a._list = [] In [67]: a Out[67]: [] Super._list is spelled with a single underscore. Double underscore would have protected it from this last bit, but would have broken the implementation of methods in subclasses. Not sure why; I think because double underscore is private, and private means private. So ultimately this whole scheme relies on a gentleman's agreement not to reach in and muck with Super._list directly, as in line 65 above. Would love to know if there's a safer way to do that.

    Read the article

  • About shared (static) Members and its behavior

    - by Allende
    I just realized that I can access shared members from instances of classes (probably this is not correct, but compile and run), and also learn/discover that, I can modify shared members, then create a new instance and access the new value of the shared member. My question is, what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ? is it totally bad ? is it valid in some cases ?. If you want to test my point here is the code (console project vb.net) that I used to test shared members, as you can see/compile/run, the shared member "x" of the class "Hello" has default value string "Default", but at runtime it changes it, and after creating a new object of that class, this object has the new value of the shared member. Module Module1 Public Class hello Public Shared x As String = "Default" Public Sub New() End Sub End Class Sub Main() Console.WriteLine("hello.x=" & hello.x) Dim obj As New hello() Console.WriteLine("obj.x=" & obj.x) obj.x = "Default shared memeber, modified in object" Console.WriteLine("obj.x=" & obj.x) hello.x = "Defaul shared member, modified in class" Console.WriteLine("hello.x=" & hello.x) Dim obj2 As New hello() Console.WriteLine("obj2.x=" & obj2.x) Console.ReadLine() End Sub End Module UPDATE: First at all, thanks to everyone, each answer give feedback, I suppose, by respect I should choose one as "the answer", I don't want to be offensive to anyone, so please don't take it so bad if I didn't choose you answer.

    Read the article

  • Foolishness Check: PHP Class finds Class file but not Class in the file.

    - by Daniel Bingham
    I'm at a loss here. I've defined an abstract superclass in one file and a subclass in another. I have required the super-classes file and the stack trace reports to find an include it. However, it then returns an error when it hits the 'extends' line: Fatal error: Class 'HTMLBuilder' not found in View/Markup/HTML/HTML4.01/HTML4_01Builder.php on line 7. I had this working with another class tree that uses factories a moment ago. I just added the builder layer in between the factories and the consumer. The factory layer looked almost exactly the same in terms of includes and dependencies. So that makes me think I must have done something silly that's causes the HTMLBuilder.php file to not be included correctly or interpreted correctly or some such. Here's the full stack trace (paths slightly altered): # Time Memory Function Location 1 0.0001 53904 {main}( ) ../index.php:0 2 0.0002 67600 require_once( 'View/Page.php' ) ../index.php:3 3 0.0003 75444 require_once( 'View/Sections/SectionFactory.php' ) ../Page.php:4 4 0.0003 81152 require_once( 'View/Sections/HTML/HTMLSectionFactory.php' ) ../SectionFactory.php:3 5 0.0004 92108 require_once( 'View/Sections/HTML/HTMLTitlebarSection.php' ) ../HTMLSectionFactory.php:5 6 0.0005 99716 require_once( 'View/Markup/HTML/HTMLBuilder.php' ) ../HTMLTitlebarSection.php:3 7 0.0005 103580 require_once( 'View/Markup/MarkupBuilder.php' ) ../HTMLBuilder.php:3 8 0.0006 124120 require_once( 'View/Markup/HTML/HTML4.01/HTML4_01Builder.php' ) ../MarkupBuilder.php:3 Here's the code in question: Parent class (View/Markup/HTML/HTMLBuilder.php): <?php require_once('View/Markup/MarkupBuilder.php'); abstract class HTMLBuilder extends MarkupBuilder { public abstract function getLink($text, $href); public abstract function getImage($src, $alt); public abstract function getDivision($id, array $classes=NULL, array $children=NULL); public abstract function getParagraph($text, array $classes=NULL, $id=NULL); } ?> Child Class, (View/Markup/HTML/HTML4.01/HTML4_01Builder.php): <?php require_once('HTML4_01Factory.php'); require_once('View/Markup/HTML/HTMLBuilder.php'); class HTML4_01Builder extends HTMLBuilder { private $factory; public function __construct() { $this->factory = new HTML4_01Factory(); } public function getLink($href, $text) { $link = $this->factory->getA(); $link->addAttribute('href', $href); $link->addChild($this->factory->getText($text)); return $link; } public function getImage($src, $alt) { $image = $this->factory->getImg(); $image->addAttribute('src', $src); $image->addAttribute('alt', $alt); return $image; } public function getDivision($id, array $classes=NULL, array $children=NULL) { $div = $this->factory->getDiv(); $div->setID($id); if(!empty($classes)) { $div->addClasses($classes); } if(!empty($children)) { $div->addChildren($children); } return $div; } public function getParagraph($text, array $classes=NULL, $id=NULL) { $p = $this->factory->getP(); $p->addChild($this->factory->getText($text)); if(!empty($classes)) { $p->addClasses($classes); } if(!empty($id)) { $p->setID($id); } return $p; } } ?> I would appreciate any and all ideas. I'm at a complete loss here as to what is going wrong. I'm sure it's something stupid I just can't see...

    Read the article

  • ctags doesn't work when class is defined like "class Gem::SystemExitException"

    - by dan
    You can define a class in a namespace like this class Gem class SystemExitException end end or class Gem::SystemExitException end When code uses first method of class definition, ctags indexes the class definition like this: SystemExitException test_class.rb /^ class SystemExitException$/;" c class:Gem With the second way, ctags indexes it like this: Gem rubygems/exceptions.rb /^class Gem::SystemExitException < SystemExit$/;" c The problem with the second way is that you can't put your cursor (in vim) over a reference to "Gem::SystemExitException" and have that jump straight to the class definition. Your only recourse is to page through all the (110!) class definitions that start with "Gem::" and find the one you're looking for. Does anyone know of a workaround? Maybe I should report this to the maintainer of ctags?

    Read the article

  • Classes, constructor and pointer class members

    - by pocoa
    I'm a bit confused about the object references. Please check the examples below: class ListHandler { public: ListHandler(vector<int> &list); private: vector<int> list; } ListHandler::ListHandler(vector<int> &list) { this->list = list; } Here I would be wasting memory right? So the right one would be: class ListHandler { public: ListHandler(vector<int>* list); private: vector<int>* list; } ListHandler::ListHandler(vector<int>* list) { this->list = list; } ListHandler::~ListHandler() { delete list; }

    Read the article

  • best alternative to in-definition initialization of static class members? (for SVN keywords)

    - by Jeff
    I'm storing expanded SVN keyword literals for .cpp files in 'static char const *const' class members and want to store the .h descriptions as similarly as possible. In short, I need to guarantee single instantiation of a static member (presumably in a .cpp file) to an auto-generated non-integer literal living in a potentially shared .h file. Unfortunately the language makes no attempt to resolve multiple instantiations resulting from assignments made outside class definitions and explicitly forbids non-integer inits inside class definitions. My best attempt (using static-wrapping internal classes) is not too dirty, but I'd really like to do better. Does anyone have a way to template the wrapper below or have an altogether superior approach? // Foo.h: class with .h/.cpp SVN info stored and logged statically class Foo { static Logger const verLog; struct hInfoWrap; public: static hInfoWrap const hInfo; static char const *const cInfo; }; // Would like to eliminate this per-class boilerplate. struct Foo::hInfoWrap { hInfoWrapper() : text("$Id$") { } char const *const text; }; ... // Foo.cpp: static inits called here Foo::hInfoWrap const Foo::hInfo; char const *const Foo::cInfo = "$Id$"; Logger const Foo::verLog(Foo::cInfo, Foo::hInfo.text); ... // Helper.h: output on construction, with no subsequent activity or stored fields class Logger { Logger(char const *info1, char const *info2) { cout << info0 << endl << info1 << endl; } }; Is there a way to get around the static linkage address issue for templating the hInfoWrap class on string literals? Extern char pointers assigned outside class definitions are linguistically valid but fail in essentially the same manner as direct member initializations. I get why the language shirks the whole resolution issue, but it'd be very convenient if an inverted extern member qualifier were provided, where the definition code was visible in class definitions to any caller but only actually invoked at the point of a single special declaration elsewhere. Anyway, I digress. What's the best solution for the language we've got, template or otherwise? Thanks!

    Read the article

  • Class Plugins in PHP?

    - by YuriKolovsky
    i just got some more questions while learning PHP, does php implement any built in plugin system? so the plugin would be able to change the behavior of the core component. for example something like this works: include 'core.class.php'; include 'plugin1.class.php'; include 'plugin2.class.php'; new plugin2; where core.class.php contains class core { public function coremethod1(){ echo 'coremethod1'; } public function coremethod2(){ echo 'coremethod2'; } } plugin1.class.php contains class plugin1 extends core { public function coremethod1(){ echo 'plugin1method1'; } } plugin2.class.php contains class plugin2 extends plugin1 { public function coremethod2(){ echo 'plugin2method2'; } } This would be ideal, if not for the problem that now the plugins are dependable on each other, and removing one of the plugins: include 'core.class.php'; //include 'plugin1.class.php'; include 'plugin2.class.php'; new plugin2; breaks the whole thing... are there any proper methods to doing this? if there are not, them i might consider moving to a different langauge that supports this... thanks for any help.

    Read the article

  • Interface vs Abstract Class (general OO)

    - by Kave
    Hi, I have had recently two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I dont know what it is. From my experience I think the following is true, if i am missing a major point please let me know: Interface: Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces. Abstract Class Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#. 1) After all that the interviewer came up with the question What if you had an Abstract class with only abstract methods, how would that be different from an interface? I didnt know the answer but I think its the inheritance as mentioned above right? 2) An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either. Many Thanks for clarification, Kave See Also: When to use an interface instead of an abstract class and vice versa Interfaces vs. Abstract Classes How do you decide between using an Abstract Class and an Interface?

    Read the article

  • PHP Access property of a class from within a class instantiated in the original class.

    - by Iain
    I'm not certain how to explain this with the correct terms so maybe an example is the best method... $master = new MasterClass(); $master->doStuff(); class MasterClass { var $a; var $b; var $c; var $eventProccer; function MasterClass() { $this->a = 1; $this->eventProccer = new EventProcess(); } function printCurrent() { echo '<br>'.$this->a.'<br>'; } function doStuff() { $this->printCurrent(); $this->eventProccer->DoSomething(); $this->printCurrent(); } } class EventProcess { function EventProcess() {} function DoSomething() { // trying to access and change the parent class' a,b,c properties } } My problem is i'm not certain how to access the properties of the MasterClass from within the EventProcess-DoSomething() method? I would need to access, perform operations on and update the properties. The a,b,c properties will be quite large arrays and the DoSomething() method would be called many times during the execuction of the script. Any help or pointers would be much appreciated :)

    Read the article

  • Define data members within constructor

    - by bertsisterwanda
    I have got this little snippet of code, I want to be able to define each array element as a new data member. class Core_User { protected $data_memebers = array( 'id' = '%d', 'email' = '"%s"', 'password' = '"%s"', 'title' = '"%s"', 'first_name' = '"%s"', 'last_name' = '"%s"', 'time_added' = '%d' , 'time_modified' = '%d' , ); function __construct($id = 0, $data = NULL) { foreach($data_memebers as $member){ //protected new data member } }

    Read the article

  • DataAnnotation attributes buddy class strangeness - ASP.NET MVC

    - by JK
    Given this POCO class that was automatically generated by an EntityFramework T4 template (has not and can not be manually edited in any way): public partial class Customer { [Required] [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")] [DisplayName("Customer Number")] public virtual string CustomerNumber { get;set; } [Required] [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")] [DisplayName("ACNumber")] public virtual string ACNumber{ get;set; } } Note that "ACNumber" is a badly named database field, so the autogenerator is unable to generate the correct display name and error message which should be "Account Number". So we manually create this buddy class to add custom attributes that could not be automatically generated: [MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode] // This line does not work public virtual string CustomerNumber { get;set; } [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")] [DisplayName("Account Number")] public virtual string ACNumber { get;set; } } Where [NumberCode] is a simple regex based attribute that allows only digits and hyphens: [AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } } NOW, when I load the page, the DisplayName attribute works correctly - it shows the display name from the buddy class not the generated class. The StringLength attribute does not work correctly - it shows the error message from the generated class ("ACNumber" instead of "Account Number"). BUT the [NumberCode] attribute in the buddy class does not even get applied to the AccountNumber property: foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) { // This collection correctly contains all the [Required], [StringLength] attributes // BUT does not contain the [NumberCode] attribute ApplyValidation(generator, attrib); } Why does the prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute which inherits ValidationAttribute so it should be there. If I manually move the [NumberCode] attribute to the autogenerated class, then it is included in the prop.Attributes.OfType<ValidationAttribute>() collection. So what I don't understand is why this particular attribute does not work in when in the buddy class, when other attributes in the buddy class do work. And why this attribute works in the autogenerated class, but not in the buddy. Any ideas? Also why does DisplayName get overriden by the buddy, when StringLength does not?

    Read the article

  • conflicting declaration when filling a static std::map class member variable

    - by Max
    I have a class with a static std::map member variable that maps chars to a custom type Terrain. I'm attempting to fill this map in the class's implementation file, but I get several errors. Here's my header file: #ifndef LEVEL_HPP #define LEVEL_HPP #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "libtcod.hpp" namespace yarl { namespace level { class Terrain { // Member Variables private: std::bitset<5> flags; // Member Functions public: explicit Terrain(const std::string& flg) : flags(flg) {} (...) }; class Level { private: static std::map<char, Terrain> terrainTypes; (...) }; } } #endif and here's my implementation file: #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "Level.hpp" #include "libtcod.hpp" using namespace std; namespace yarl { namespace level { /* fill Level::terrainTypes */ map<char,Terrain> Level::terrainTypes['.'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[','] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['\''] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['`'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[178] = Terrain("11111"); // wall (...) } } I'm using g++, and the errors I get are src/Level.cpp:15: error: conflicting declaration ‘std::map, std::allocator yarl::level::Level::terrainTypes [46]’ src/Level.hpp:104: error: ‘yarl::level::Level::terrainTypes’ has a previous declaration as ‘std::map, std::allocator yarl::level::Level::terrainTypes’ src/Level.cpp:15: error: declaration of ‘std::map, std::allocator yarl::level::Level::terrainTypes’ outside of class is not definition src/Level.cpp:15: error: conversion from ‘yarl::level::Terrain’ to non-scalar type ‘std::map, std::allocator ’ requested src/Level.cpp:15: error: ‘yarl::level::Level::terrainTypes’ cannot be initialized by a non-constant expression when being declared I get a set of these for each map assignment line in the implementation file. Anyone see what I'm doing wrong? Thanks for your help.

    Read the article

  • Why and when should I make a class 'static'? What is the purpose of 'static' keyword on classes?

    - by Saeed Neamati
    The static keyword on a member in many languages mean that you shouldn't create an instance of that class to be able to have access to that member. However, I don't see any justification to make an entire class static. Why and when should I make a class static? What benefits do I get from making a class static? I mean, after declaring a static class, one should still declare all members which he/she wants to have access to without instantiation, as static too. This means that for example, Math class could be declared normal (not static), without affecting how developers code. In other words, making a class static or normal is kind of transparent to developers.

    Read the article

  • Java Design Questions - Class, Function, Access Modifiers

    - by Ron
    I am newbie to Java. I have some design questions. Say I have a crawler application, that does the following: 1. Crawls a url and gets its content 2. Parses the contents 3. Displays the contents How do you decide between implementing a function or a class? -- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well? -- If it should be a class, should it be protected or public class? How do you decide between implementing a public or protected class? -- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public? Thanks Ron

    Read the article

  • get static initialization block to run in a java without loading the class

    - by TP
    I have a few classes as shown here public class TrueFalseQuestion implements Question{ static{ QuestionFactory.registerType("TrueFalse", "Question"); } public TrueFalseQuestion(){} } ... public class QuestionFactory { static final HashMap<String, String > map = new HashMap<String,String>(); public static void registerType(String questionName, String ques ) { map.put(questionName, ques); } } public class FactoryTester { public static void main(String[] args) { System.out.println(QuestionFactory.map.size()); // This prints 0. I want it to print 1 } } How can I change TrueFalseQuestion Type so that the static method is always run so that I get 1 instead of 0 when I run my main method? I do not want any change in the main method. I am actually trying to implement the factory patterns where the subclasses register with the factory but i have simplified the code for this question.

    Read the article

  • How can I load class's part using linq to sql without anonymous class or additional class?

    - by ais
    class Test { int Id{get;set;} string Name {get;set;} string Description {get;set;} } //1)ok context.Tests.Select(t => new {t.Id, t.Name}).ToList().Select(t => new Test{Id = t.Id, Name = t.Name}); //2)ok class TestPart{ int Id{get;set;} string Name {get;set;} } context.Tests.Select(t => new TestPart{Id = t.Id, Name = t.Name}).ToList().Select(t => new Test{Id = t.Id, Name = t.Name}); //3)error Explicit construction of entity type 'Test' in query is not allowed. context.Tests.Select(t => new Test{Id = t.Id, Name = t.Name}).ToList(); Is there any way to use third variant?

    Read the article

  • question about class derivation in c++?

    - by jack22
    hi, i want to know some things about class derivation in c++ so i have super class x and an inherited class y and i did this class x{ public:a; private:b; protected:c; } class y:public x{ public:d; } in this case how y can access a,b,and c and by how i mean(public,protected,private) the second case: class x{ public:a; private:b; protected:c; } class y:private x{ public:d; } the same question? the third case: class x{ public:a; private:b; protected:c; } class y:private x{ public:d; } again the same question? sorry i think i wrote too much bye

    Read the article

  • how can we call one class's method through another class's object in php

    - by hello
    I want to know that is there any method in PHP by which i can call one class's method from another class object. let me clear here is one class class A() { public function showData(){ //here is method of class A } } // here is another class class B(){ public function getData(){ //some method in class B } } //now i create two objects $objA= new class A(); $objB=new class B(); now i want to call this $objB->showData();<--- is that possible .. by any how method( using public, inheritence,child parent etc...) please help me

    Read the article

  • JQuery: loop through elements with more than one css class name that share only the first class name

    - by omaether
    Hello, I'm trying to use JQuery to loop through several div's with more than one class name, that all have the same first css class name and each one has a different second class name, e.g. <div class="maintext blue"> </div> <div class="maintext purple"> </div> <div class="maintext chartreuse"> </div> <div class="maintext puce"> </div> <div class="maintext lime"> </div> In JQuery I have tried $(".mainText").each(function (i) $(".mainText.*").each(function (i) $(".mainText" *).each(function (i) $(".mainText .*").each(function (i) But it will not select any of the divs with class="mainText ..." thanks for considering the question.

    Read the article

  • Give a reference to a python instance attribute at class definition

    - by Guenther Jehle
    I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(object): def __init__(self, interface, name): self.interface=interface self.name=name def get(self): return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port) class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface.port=port if __name__=="__main__": d1=Device("Foo") print d1.value1.get() # >>> Getting Value "value1" with interface "Foo" d2=Device("Bar") print d2.value1.get() # >>> Getting Value "value1" with interface "Bar" print d1.value1.get() # >>> Getting Value "value1" with interface "Bar" The last print is wrong, cause d1 should have the interface "Foo". I know whats going wrong: The line interface=Interface() line is executed, when the class definition is parsed (once). So every Device class has the same instance of interface. I could change the Device class to: class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface=Interface() self.interface.port=port So this is also not working: The values still have the reference to the original interface instance and the self.interface is just another instance... The output now is: >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" So how could I solve this the pythonic way? I could setup a function in the Device class to look for attributes with type Value and reassign them the new interface. Isn't this a common problem with a typical solution for it? Thanks!

    Read the article

  • Which is the better C# class design for dealing with read+write versus readonly

    - by DanM
    I'm contemplating two different class designs for handling a situation where some repositories are read-only while others are read-write. (I don't foresee any need to a write-only repository.) Class Design 1 -- provide all functionality in a base class, then expose applicable functionality publicly in sub classes public abstract class RepositoryBase { protected virtual void SelectBase() { // implementation... } protected virtual void InsertBase() { // implementation... } protected virtual void UpdateBase() { // implementation... } protected virtual void DeleteBase() { // implementation... } } public class ReadOnlyRepository : RepositoryBase { public void Select() { SelectBase(); } } public class ReadWriteRepository : RepositoryBase { public void Select() { SelectBase(); } public void Insert() { InsertBase(); } public void Update() { UpdateBase(); } public void Delete() { DeleteBase(); } } Class Design 2 - read-write class inherits from read-only class public class ReadOnlyRepository { public void Select() { // implementation... } } public class ReadWriteRepository : ReadOnlyRepository { public void Insert() { // implementation... } public void Update() { // implementation... } public void Delete() { // implementation... } } Is one of these designs clearly stronger than the other? If so, which one and why? P.S. If this sounds like a homework question, it's not, but feel free to use it as one if you want :)

    Read the article

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