Search Results

Search found 1523 results on 61 pages for 'assignment'.

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

  • JS assignment order of properties in objects

    - by devdev
    Just had a quick question about why a certain order of assignment works and another doesn't. I wanted to create a simple "inherit" / "copy" function (just for testing it) that copies properties from one object to another: var cat = { tail:"yes", hairy:"yes, hairy" }; var dog = { sick:"extremely ill"}; function inherit(obj1, obj2) { for (var p in obj1) { obj2[p] = obj1[p]; // this works, but "obj1[p] = obj2[p];" doesn't. Why?? } } inherit(cat, dog); console.log(dog.tail);

    Read the article

  • c++: truth assignment warning with arguments?

    - by John
    I use the following to work with arguments in my programs, but it seems to just hand me a warning (just a warning): "warning: suggest parentheses around assignment used as truth value" The beginning of the code is as follows: enum{OPT_DISP_H = 0x2, OPT_DISP_W = 0x1}; int main(int argc, char *argv[]) { int opt = 0x00; char c; while((++argv)[0] && argv[0][0]=='-'){ while(c =* ++argv[0]) switch(c){ case 'h': opt |= OPT_DISP_H; break; //etc.. The while(c =* ++argv[0]) part being where the warning persists. The code works fine, but what does this warning mean opposed to what is used? I think the code is c = *++argv[0], using the pointer. So why does the single = work and what is really recommended to be used?

    Read the article

  • C++ Generic List Assignment

    - by S73417H
    I've clearly been stuck in Java land for too long... Is it possible to do the C++ equivalent of the following Java code: // Method List<Bar> getBars() { return new LinkedList<Bar>(); } // Assignment statement. List<Foo> stuff = getBars(); Where Foo is a sub-class of Bar. So in C++.... std::list<Bar> & getBars() { std::list<Bar> bars; return bars; } std::list<Foo> stuff = getBars(); Hope that makes sense....

    Read the article

  • Incompatible type in assignment

    - by coure06
    Getting error: Incompatible type in assignment at fValue = ..., see the code static float t = 0; float d = .5; static float fValue = 0; fValue = [self easeOutBounce:t andB:0 andC:30 andD:d]; here is the method -(float) easeOutBounce:(float)t andB:(float)b andC:(float)c andD:(float)d { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))t + .75) + b; } else if (t < (2.5/2.75)) { return c(7.5625*(t-=(2.25/2.75))t + .9375) + b; } else { return c(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }

    Read the article

  • Overloading assignment operator in C#

    - by Carson Myers
    I know the = operator can't be overloaded, but there must be a way to do what I want here: I'm just creating classes to represent quantitative units, since I'm doing a bit of physics. Apparently I can't just inherit from a primitive, but I want my classes to behave exactly like primitives -- I just want them typed differently. So I'd be able to go, Velocity ms = 0; ms = 17.4; ms += 9.8; etc. I'm not sure how to do this. I figured I'd just write some classes like so: class Power { private Double Value { get; set; } //operator overloads for +, -, /, *, =, etc } But apparently I can't overload the assignment operator. Is there any way I can get this behavior?

    Read the article

  • Solving C++ 'target of assignment not really an lvalue' errors

    - by Jason
    Given this code: void FrMemCopy(void *to, const void *from, size_t sz) { size_t sz8 = sz >> 3; size_t sz1 = sz - (sz8 << 3); while (sz8-- != 0) { *((double *)to)++ = *((double *)from)++; } while (sz1-- != 0) { *((char *)to)++ = *((char *)from)++; } } I am receiving target of assignment not really an lvalue warnings on the 2 lines inside the while loops. Can anyone break down those lines? a cast then an increment? What is a simplier way to write that? What does the error mean?

    Read the article

  • assignment from incompatible pointer type

    - by Hristo
    I have set up the following struct: typedef struct _thread_node_t { pthread_t thread; struct thread_node_t *next; } thread_node_t; ... and then I have defined: // create thread to for incoming connection thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t)); pthread_create(&(thread_node->thread), NULL, client_thread, &csFD); thread_node->next = thread_arr; // assignment from incompatible pointer type thread_arr = thread_node; where thread_arr is thread_node_t *thread_arr = NULL; I don't understand why the compiler is complaining. Maybe I'm misunderstanding something.

    Read the article

  • C++ assignment operators dynamic arrays

    - by user2905445
    First off i know the multiplying part is wrong but i have some questions about the code. 1. When i am overloading my operator+ i print out the matrix using cout << *this then right after i return *this and when i do a+b on matix a and matix b it doesnt give me the same thing this is very confusing. 2. When i make matrix c down in my main i cant use my default constructor for some reason because when i go to set it = using my assignment operator overloaded function it gives me an error saying "expression must be a modifiable value. although using my constructor that sets the row and column numbers is the same as my default constructor using (0,0). 3. My assignment operator= function uses a copy constructor to make a new matrix using the values on the right hand side of the equal sign and when i print out c it doesn't give me anything Any help would be great this is my hw for a algorithm class which i still need to do the algorithm for the multiplying matrices but i need to solve these issues first and im having a lot of trouble please help. //Programmer: Eric Oudin //Date: 10/21/2013 //Description: Working with matricies #include <iostream> using namespace std; class matrixType { public: friend ostream& operator<<(ostream&, const matrixType&); const matrixType& operator*(const matrixType&); matrixType& operator+(const matrixType&); matrixType& operator-(const matrixType&); const matrixType& operator=(const matrixType&); void fillMatrix(); matrixType(); matrixType(int, int); matrixType(const matrixType&); ~matrixType(); private: int **matrix; int rowSize; int columnSize; }; ostream& operator<< (ostream& osObject, const matrixType& matrix) { osObject << endl; for (int i=0;i<matrix.rowSize;i++) { for (int j=0;j<matrix.columnSize;j++) { osObject << matrix.matrix[i][j] <<", "; } osObject << endl; } return osObject; } const matrixType& matrixType::operator=(const matrixType& matrixRight) { matrixType temp(matrixRight); cout << temp; return temp; } const matrixType& matrixType::operator*(const matrixType& matrixRight) { matrixType temp(rowSize*matrixRight.columnSize, columnSize*matrixRight.rowSize); if(rowSize == matrixRight.columnSize) { for (int i=0;i<rowSize;i++) { for (int j=0;j<columnSize;j++) { temp.matrix[i][j] = matrix[i][j] * matrixRight.matrix[i][j]; } } } else { cout << "Cannot multiply matricies that have different size rows from the others columns." << endl; } return temp; } matrixType& matrixType::operator+(const matrixType& matrixRight) { if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize) { for (int i=0;i<rowSize;i++) { for (int j=0;j<columnSize;j++) { matrix[i][j] += matrixRight.matrix[i][j]; } } } else { cout << "Cannot add matricies that are different sizes." << endl; } cout << *this; return *this; } matrixType& matrixType::operator-(const matrixType& matrixRight) { matrixType temp(rowSize, columnSize); if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize) { for (int i=0;i<rowSize;i++) { for (int j=0;j<columnSize;j++) { matrix[i][j] -= matrixRight.matrix[i][j]; } } } else { cout << "Cannot subtract matricies that are different sizes." << endl; } return *this; } void matrixType::fillMatrix() { for (int i=0;i<rowSize;i++) { for (int j=0;j<columnSize;j++) { cout << "Enter the matix number at (" << i << "," << j << "):"; cin >> matrix[i][j]; } } } matrixType::matrixType() { rowSize=0; columnSize=0; matrix = new int*[rowSize]; for (int i=0; i < rowSize; i++) { matrix[i] = new int[columnSize]; } } matrixType::matrixType(int setRows, int setColumns) { rowSize=setRows; columnSize=setColumns; matrix = new int*[rowSize]; for (int i=0; i < rowSize; i++) { matrix[i] = new int[columnSize]; } } matrixType::matrixType(const matrixType& otherMatrix) { rowSize=otherMatrix.rowSize; columnSize=otherMatrix.columnSize; matrix = new int*[rowSize]; for (int i = 0; i < rowSize; i++) { for (int j = 0; j < columnSize; j++) { matrix[i]=new int[columnSize]; matrix[i][j]=otherMatrix.matrix[i][j]; } } } matrixType::~matrixType() { delete [] matrix; } int main() { matrixType a(2,2); matrixType b(2,2); matrixType c(0,0); cout << "fill matrix a:"<< endl;; a.fillMatrix(); cout << "fill matrix b:"<< endl;; b.fillMatrix(); cout << a; cout << b; c = a+b; cout <<"matrix a + matrix b =" << c; system("PAUSE"); return 0; }

    Read the article

  • How to approach copying objects with smart pointers as class attributes?

    - by tomislav-maric
    From the boost library documentation I read this: Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed. I have a very simple problem: I want to use RAII for pointer attributes of a class that is Copyable and Assignable. The copy and assignment operations should be deep: every object should have its own copy of the actual data. Also, RTTI needs to be available for the attributes (their type may also be determined at runtime). Should I be searching for an implementation of a Copyable smart pointer (the data are small, so I don't need Copy on Write pointers), or do I delegate the copy operation to the copy constructors of my objects as shown in this answer? Which smart pointer do I choose for simple RAII of a class that is copyable and assignable? (I'm thinking that the unique_ptr with delegated copy/assignment operations to the class copy constructor and assignment operator would make a proper choice, but I am not sure) Here's a pseudocode for the problem using raw pointers, it's just a problem description, not a running C++ code: // Operation interface class ModelOperation { public: virtual void operate = (); }; // Implementation of an operation called Special class SpecialModelOperation : public ModelOperation { private: // Private attributes are present here in a real implementation. public: // Implement operation void operate () {}; }; // All operations conform to ModelOperation interface // These are possible operation names: // class MoreSpecialOperation; // class DifferentOperation; // Concrete model with different operations class MyModel { private: ModelOperation* firstOperation_; ModelOperation* secondOperation_; public: MyModel() : firstOperation_(0), secondOperation_(0) { // Forgetting about run-time type definition from input files here. firstOperation_ = new MoreSpecialOperation(); secondOperation_ = new DifferentOperation(); } void operate() { firstOperation_->operate(); secondOperation_->operate(); } ~MyModel() { delete firstOperation_; firstOperation_ = 0; delete secondOperation_; secondOperation_ = 0; } }; int main() { MyModel modelOne; // Some internal scope { // I want modelTwo to have its own set of copied, not referenced // operations, and at the same time I need RAII to work for it, // as soon as it goes out of scope. MyModel modelTwo (modelOne); } return 0; }

    Read the article

  • ReSharper - Possible Null Assignment when using Microsoft.Contracts

    - by HVS
    Is there any way to indicate to ReSharper that a null reference won't occur because of Design-by-Contract Requires checking? For example, the following code will raise the warning (Possible 'null' assignment to entity marked with 'NotNull' attribute) in ReSharper on lines 7 and 8: private Dictionary<string, string> _Lookup = new Dictionary<string, string>(); public void Foo(string s) { Contract.Requires(!String.IsNullOrEmpty(s)); if (_Lookup.ContainsKey(s)) _Lookup.Remove(s); } What is really odd is that if you remove the Contract.Requires(...) line, the ReSharper message goes away. Update I found the solution through ExternalAnnotations which was also mentioned by Mike below. Here's an example of how to do it for a function in Microsoft.Contracts: Create a directory called Microsoft.Contracts under the ExternalAnnotations ReSharper directory. Next, Create a file called Microsoft.Contracts.xml and populate like so: <assembly name="Microsoft.Contracts"> <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> </assembly> Restart Visual Studio, and the message goes away!

    Read the article

  • trying to make a simple grid-class, non-lvalue in assignment

    - by Tyrfing
    I'm implementing a simple C++ grid class. One Function it should support is accessed through round brackets, so that I can access the elements by writing mygrid(0,0). I overloaded the () operator and i am getting the error message: "non-lvalue in assignment". what I want to be able to do: //main cGrid<cA*> grid(5, 5); grid(0,0) = new cA(); excerpt of my implementation of the grid class: template class cGrid { private: T* data; int mWidth; int mHeight; public: cGrid(int width, int height) : mWidth(width), mHeight(height) { data = new T[width*height]; } ~cGrid() { delete data; } T operator ()(int x, int y) { if (x >= 0 && x <= mWidth) { if (y >= 0 && y <= mHeight) { return data[x + y * mWidth]; } } } const T &operator ()(int x, int y) const { if (x >= 0 && x <= mWidth) { if (y >= 0 && y <= mHeight) { return data[x + y * mWidth]; } } } The rest of the code deals with the implementation of an iterator and should not be releveant.

    Read the article

  • jsprf.c:644: error: incompatible types in assignment

    - by giantKamote
    Hey guys, Can you help me with this error I encountered while building Spidermonkey in PPC? make -f Makefile.ref cat: ../../dist/Linux_All_DBG.OBJ/nspr/Version: No such file or directory cd editline; make -f Makefile.ref all make[1]: Entering directory `/units/ spidermonkey-1.8-next-wip/src/editline' make[1]: Nothing to be done for `all'. make[1]: Leaving directory `/units/ spidermonkey-1.8-next-wip/src/editline' make -f Makefile.ref Linux_All_DBG.OBJ/libjs.a Linux_All_DBG.OBJ/ libjs.so Linux_All_DBG.OBJ/js Linux_All_DBG.OBJ/jsautocfg.h Linux_All_DBG.OBJ/jscpucfg Linux_All_DBG.OBJ/jscpucfg.o cat: ../../dist/Linux_All_DBG.OBJ/nspr/Version: No such file or directory make[1]: Entering directory `/units/ spidermonkey-1.8-next-wip/src' make[1]: Circular jscpucfg.h <- Linux_All_DBG.OBJ/jsautocfg.h dependency dropped. make[1]: Circular Linux_All_DBG.OBJ/jsautocfg.h <- Linux_All_DBG.OBJ/ jsautocfg.h dependency dropped. /powerpc-750- linux-gnu_gcc-3.4.6/bin/powerpc-750-linux-gnu-gcc -o Linux_All_DBG.OBJ/ jsprf.o -c -Wall -Wno-format -MMD -DGCC_OPT_BUG -g3 -DXP_UNIX -DSVR4 - DSYSV -D_BSD_SOURCE -DPOSIX_SOURCE -DHAVE_LOCALTIME_R -DX86_LINUX - DDEBUG -DDEBUG_build -DEDITLINE -ILinux_All_DBG.OBJ jsprf.c jsprf.c: In function `BuildArgArray': jsprf.c:644: error: incompatible types in assignment make[1]: *** [Linux_All_DBG.OBJ/jsprf.o] Error 1 make[1]: Leaving directory `/units/ spidermonkey-1.8-next-wip/src' make: *** [all] Error 2 I'm using a Redhat-Linux machine. Do I need to have NSPR too to cross-compile spidermonkey? Thanks a lot!!

    Read the article

  • warning: assignment makes pointer from integer without a cast

    - by FILIaS
    Im new in programming c with arrays and files. Im just trying to run the following code but i get warnings like that: warning: assignment makes pointer from integer without a cast Any help? It might be silly... but I cant find what's wrong. FILE *fp; FILE *cw; char filename_game[40],filename_words[40]; int main() { while(1) { /* Input filenames. */ printf("\n Enter the name of the file with the cryptwords array: \n"); gets(filename_game); printf("\n Give the name of the file with crypted words:\n"); gets(filename_words); /* Try to open the file with the game */ if (fp=fopen("crypt.txt","r")!=NULL) { printf("\n Successful opening %s \n",filename_game); fclose(fp); puts("\n Enter x to exit,any other to continue! \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_game); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } /* Try to open the file with the names. */ if (cw=fopen("words.txt","r")!=NULL) { printf("\n Successful opening %s \n",filename_words); fclose(cw); puts("\n Enter x to exit,any other to continue \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_words); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } } return 0; }

    Read the article

  • c incompatible types in assignment, problem with pointers?

    - by Fantastic Fourier
    Hi I'm working with C and I have a question about assigning pointers. struct foo { int _bar; char * _car[MAXINT]; // this is meant to be an array of char * so that it can hold pointers to names of cars } int foofunc (void * arg) { int bar; char * car[MAXINT]; struct foo thing = (struct foo *) arg; bar = arg->_bar; // this works fine car = arg->_car; // this gives compiler errors of incompatible types in assignment } car and _car have same declaration so why am I getting an error about incompatible types? My guess is that it has something to do with them being pointers (because they are pointers to arrays of char *, right?) but I don't see why that is a problem. when i declared char * car; instead of char * car[MAXINT]; it compiles fine. but I don't see how that would be useful to me later when I need to access certain info using index, it would be very annoying to access that info later. in fact, I'm not even sure if I am going about the right way, maybe there is a better way to store a bunch of strings instead of using array of char *?

    Read the article

  • SQL Distinct keyword in assignment statement

    - by Brandi
    I have a query that works: DECLARE @ProductID int SET @ProductID = '1234' SELECT DISTINCT TOP 12 a.ProductID FROM A a WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE b.ProductID = @ProductID) AND a.ProductID != @ProductID It returns a list of 12 product numbers, all unique. I need to store these results in a variable, comma separated, because that's what 3rd party stored procedure needs. So I have this: DECLARE @ProductID int DECLARE @relatedprods varchar(8000) SET @ProductID = '1234' SET @relatedprods = '' SELECT TOP 12 @relatedprods = @relatedprods + CONVERT(VARCHAR(20), a.ProductID) + ', ' FROM A a WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE B.ProductID = @ProductID) AND a.ProductID != @ProductID SELECT @relatedprods Now, none of these are distinct, but it is returning 12 rows. Now I add the 'distinct' back in, like in the first query: DECLARE @ProductID int DECLARE @relatedprods varchar(8000) SET @ProductID = '1234' SET @relatedprods = '' SELECT DISTINCT TOP 12 @relatedprods = @relatedprods + CONVERT(VARCHAR(20), a.ProductID) + ', ' FROM A a WHERE a.CategoryID IN (SELECT b.CategoryID FROM B b WHERE B.ProductID = @ProductID) AND a.ProductID != @ProductID SELECT @relatedprods Only one product is returned in the comma separated list! Does 'distinct' not work in assignment statements? What did I do wrong? Or is there a way to get around this? Thanks in advance!

    Read the article

  • Design for a Debate club assignment application

    - by Amir Rachum
    Hi all, For my university's debate club, I was asked to create an application to assign debate sessions and I'm having some difficulties as to come up with a good design for it. I will do it in Java. Here's what's needed: What you need to know about BP debates: There are four teams of 2 debaters each and a judge. The four groups are assigned a specific position: gov1, gov2, op1, op2. There is no significance to the order within a team. The goal of the application is to get as input the debaters who are present (for example, if there are 20 people, we will hold 2 debates) and assign them to teams and roles with regards to the history of each debater so that: Each debater should debate with (be on the same team) as many people as possible. Each debater should uniformly debate in different positions. The debate should be fair - debaters have different levels of experience and this should be as even as possible - i.e., there shouldn't be a team of two very experienced debaters and a team of junior debaters. There should be an option for the user to restrict the assignment in various ways, such as: Specifying that two people should debate together, in a specific position or not. Specifying that a single debater should be in a specific position, regardless of the partner. etc... If anyone can try to give me some pointers for a design for this application, I'll be so thankful! Also, I've never implemented a GUI before, so I'd appreciate some pointers on that as well, but it's not the major issue right now.

    Read the article

  • Multiple Unpacking Assignment in Python when you don't know the sequence length

    - by doug
    The textbook examples of multiple unpacking assignment are something like: import numpy as NP M = NP.arange(5) a, b, c, d, e = M # so of course, a = 0, b = 1, etc. M = NP.arange(20).reshape(5, 4) # numpy 5x4 array a, b, c, d, e = M # here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e) (My Q is not numpy specfic; indeed, i would prefer a pure python solution.) W/r/t the piece of code i'm looking at now, i see two complications on that straightforward scenario: i usually won't know the shape of M; and i want to unpack a certain number of items (definitely less than all items) and i want to put the remainder into a single container so back to the 5x4 array above, what i would very much like to be able to do is, for instance, assign the first three rows of M to a, b, and c respectively (exactly as above) and the rest of the rows (i have no idea how many there will be, just some positive integer) to a single container, all_the_rest = []. I'm not sure if i have explained this clearly; in any event, if i get feedback i'll promptly edit my Question.

    Read the article

  • Programming methods design phase assignment

    - by Shakir
    Hey, i have an assignment (NCC) which deals with the design phase. The Scenario is that you have four soccer divisions (divisions 1,2,3 and 4) which consist of 22 teams each and hence each team plays 42 games (home and away). The concept is similar to the barclays premier league whereby ranking is based on points or else goal difference or else goals scored by team. The difference is that the top 2 teams are promoted and the bottom 2 are relegated and this includes Div 1 and Div 4 as the top 2 of Div1 are promoted to the national league which is above division 1 regional league and bottom 2 of Div4 are relegated to the local league below Division 4 regional league. Hence there are 3 total leagues and 4 divisions in the regional league (which has 22 teams each). Now the referee has to add the result of the match and thus automatic tables have to be generated now, There are two reports League Tables for 4 divisions List of all results for any chosen team during the season by date it was played on There are a couple of things to be done... i know its gonna be terrible to make everything but atleast explain to me how i should go about drawing these and what things i should include (generally) Logical Data Structure Diagram (DSD) for each report Preliminary Program Structure (PSD) for each report Detailed Program Specification for each report Flowchart for each report There are other things but i think our teacher will give us clear "clues" for it Thanks a lot Update - Project so far: Data Structure Diagram Preliminary Program Structure

    Read the article

  • Javascript function using "this = " gives "Invalid left-hand side in assignment"

    - by Brian M. Hunt
    I am trying to get a Javascript object to use the "this" assignments of another objects' constructor, as well as assume all that objects' prototype functions. Here's an example of what I'm attempting to accomplish: /* The base - contains assignments to 'this', and prototype functions */ function ObjX(a,b) { this.$a = a, $b = b; } ObjX.prototype.getB() { return this.$b; } function ObjY(a,b,c) { // here's what I'm thinking should work: this = ObjX(a, b * 12); /* and by 'work' I mean ObjY should have the following properties: * ObjY.$a == a, ObjY.$b == b * 12, * and ObjY.getB() == ObjX.prototype.getB() * ... unfortunately I get the error: * Uncaught ReferenceError: Invalid left-hand side in assignment */ this.$c = c; // just to further distinguish ObjY from ObjX. } I'd be grateful for your thoughts on how to have ObjY subsume ObjX's assignments to 'this' (i.e. not have to repeat all the this.$* = * assignments in ObjY's constructor) and have ObjY assume ObjX.prototype. My first thought is to try the following: function ObjY(a,b,c) { this.prototype = new ObjX(a,b*12); } Ideally I'd like to learn how to do this in a prototypal way (i.e. not have to use any of those 'classic' OOP substitutes like Base2). It may be noteworthy that ObjY will be anonymous (e.g. factory['ObjX'] = function(a,b,c) { this = ObjX(a,b*12); ... }) -- if I've the terminology right. Thank you.

    Read the article

  • iOS: Assignment to iVar in Block (ARC)

    - by manmal
    I have a readonly property isFinished in my interface file: typedef void (^MyFinishedBlock)(BOOL success, NSError *e); @interface TMSyncBase : NSObject { BOOL isFinished_; } @property (nonatomic, readonly) BOOL isFinished; and I want to set it to YES in a block at some point later, without creating a retain cycle to self: - (void)doSomethingWithFinishedBlock:(MyFinishedBlock)theFinishedBlock { __weak MyClass *weakSelf = self; MyFinishedBlock finishedBlockWrapper = ^(BOOL success, NSError *e) { [weakSelf willChangeValueForKey:@"isFinished"]; weakSelf -> isFinished_ = YES; [weakSelf didChangeValueForKey:@"isFinished"]; theFinishedBlock(success, e); }; self.finishedBlock = finishedBlockWrapper; // finishedBlock is a class ext. property } I'm unsure that this is the right way to do it (I hope I'm not embarrassing myself here ^^). Will this code leak, or break, or is it fine? Perhaps there is an easier way I have overlooked? SOLUTION Thanks to the answers below (especially Krzysztof Zablocki), I was shown the way to go here: Define isFinished as readwrite property in the class extension (somehow I missed that one) so no direct ivar assignment is needed, and change code to: - (void)doSomethingWithFinishedBlock:(MyFinishedBlock)theFinishedBlock { __weak MyClass *weakSelf = self; MyFinishedBlock finishedBlockWrapper = ^(BOOL success, NSError *e) { MyClass *strongSelf = weakSelf; strongSelf.isFinished = YES; theFinishedBlock(success, e); }; self.finishedBlock = finishedBlockWrapper; // finishedBlock is a class ext. property }

    Read the article

  • How are property assignment expressions handled in C#?

    - by Serious
    In C# you can use a property as both an lrvalue and rvalue at the same time like this : int n = N = 1; Here is a complete C# sample : class Test { static int n; static int N { get { System.Console.WriteLine("get"); return n; } set { System.Console.WriteLine("set"); n = value; } } static void Main() { int n = N = 1; System.Console.WriteLine("{0}/{1}", n, N); } } You can't do that in C++/CLI as the resulting type of the assignment expression "N = 1" is void. EDIT: here is a C++/CLI sample that shows this : ref class A { public: static property int N; }; int main() { int n = A::N = 1; System::Console::WriteLine("{0}/{1}", n, A::N); } So what's the magic behind C# syntax allowing a void-expression to be used as a rvalue ? Is this special treatment only available for properties or do you know other C# tricks like this ?

    Read the article

  • Need Help finding an appropriate task assignment algorithm for a college project involving coordinat

    - by Trif Mircea
    I am a long time lurker here and have found over time many answers regarding jquery and web development topics so I decided to ask a question of my own. This time I have to create a c++ project for college which should help manage the workflow of a company providing all kinds of services through in the field teams. The ideas I have so far are: client-server application; the server is a dispatcher where all the orders from clients get and the clients are mobile devices (PDAs) each team in the field having one a order from a client is a task. Each task is made up of a series of subtasks. You have a database with estimations on how long a task should take to complete you also know what tasks or subtasks each team on the field can perform based on what kind of specialists made up the team (not going to complicate the problem by adding needed materials, it is considered that if a member of a team can perform a subtask he has the stuff needed) Now knowing these factors, what would a good task assignment algorithm be? The criteria is: how many tasks can a team do, how many tasks they have in the queue, it could also be location, how far away are they from the place but I don't think I can implement that.. It needs to be efficient and also to adapt quickly is the human dispatcher manually assigns a task. Any help or leads would be really appreciated. Also I'm not 100% sure in the idea so if you have another way you would go about creating such an application please share, even if it just a quick outline. I have to write a theoretical part too so even if the ideas are far more complex that what i outlined that would be ok ; I'd write those and implement what I can. Edit: C++ is the only language I know unfortunately.

    Read the article

  • C++ Pointer member function with templates assignment with a member function of another class

    - by Agusti
    Hi, I have this class: class IShaderParam{ public: std::string name_value; }; template<class TParam> class TShaderParam:public IShaderParam{ public: void (TShaderParam::*send_to_shader)( const TParam&,const std::string&); TShaderParam():send_to_shader(NULL){} TParam value; void up_to_shader(); }; typedef TShaderParam<float> FloatShaderParam; typedef TShaderParam<D3DXVECTOR3> Vec3ShaderParam; In another class, I have a vector of IShaderParams* and functions that i want to send to "send_to_shader". I'm trying assign the reference of these functions like this: Vec3ShaderParam *_param = new Vec3ShaderParam; _param-send_to_shader = &TShader::setVector3; This is the function: void TShader::setVector3(const D3DXVECTOR3 &vec, const std::string &name){ //... } And this is the class with IshaderParams*: class TShader{ std::vector params; public: Shader effect; std::string technique_name; TShader(std::string& afilename):effect(NULL){}; ~TShader(); void setVector3(const D3DXVECTOR3 &vec, const std::string &name); When I compile the project with Visual Studio C++ Express 2008 I recieve this error: Error 2 error C2440: '=' :can't make the conversion 'void (__thiscall TShader::* )(const D3DXVECTOR3 &,const std::string &)' a 'void (__thiscall TShaderParam::* )(const TParam &,const std::string &)' c:\users\isagoras\documents\mcv\afoc\shader.cpp 127 Can I do the assignment? No? I don't know how :-S Yes, I know that I can achieve the same objective with other techniques, but I want to know how can I do this..

    Read the article

  • Trailing comments after variable assignment subvert comparison

    - by nobar
    In GNU make, trailing comments appended to variable assignments prevent subsequent comparison (via ifeq) from working correctly. Here's the Makefile... A = a B = b ## trailing comment C = c RESULT := ifeq "$(A)" "a" RESULT += a endif ifeq "$(B)" "b" RESULT += b endif ifeq "$(C)" "c" RESULT += c endif rule: @echo RESULT=\"$(RESULT)\" @echo A=\"$(A)\" @echo B=\"$(B)\" @echo C=\"$(C)\" Here's the output... $ make RESULT=" a c" A="a" B="b " C="c" As you can see from the displayed value of RESULT, the ifeq was affected by the presence of the comment in the assignment of B. Echoing the variable B, shows that the problem is not the comment, but the intervening space. The obvious solution is to explicitly strip the whitespace prior to comparison like so... ifeq "$(strip $(B))" "b" RESULT += b endif However this seems error prone. Since the strip operation is not needed unless/until a comment is used, you can leave out the strip and everything will initially work just fine -- so chances are you won't always remember to add the strip. Later, if someone adds a comment when setting the variable, the Makefile no longer works as expected. Note: There is a closely related issue, as demonstrated in this question, that trailing whitespace can break string compares even if there is no comment. Question: Is there a more fool-proof way to deal with this issue?

    Read the article

  • C Programming - My program is good enough for my assignment but I know its not good

    - by Joe
    Hi there I'm just starting an assignment for uni and it's raised a question for me. I don't understand how to return a string from a function without having a memory leak. char* trim(char* line) { int start = 0; int end = strlen(line) - 1; /* find the start position of the string */ while(isspace(line[start]) != 0) { start++; } //printf("start is %d\n", start); /* find the position end of the string */ while(isspace(line[end]) != 0) { end--; } //printf("end is %d\n", end); /* calculate string length and add 1 for the sentinel */ int len = end - start + 2; /* initialise char array to len and read in characters */ int i; char* trimmed = calloc(sizeof(char), len); for(i = 0; i < (len - 1); i++) { trimmed[i] = line[start + i]; } trimmed[len - 1] = '\0'; return trimmed; } as you can see I am returning a pointer to char which is an array. I found that if I tried to make the 'trimmed' array by something like: char trimmed[len]; then the compiler would throw up a message saying that a constant was expected on this line. I assume this meant that for some reason you can't use variables as the array length when initialising an array, although something tells me that can't be right. So instead I made my array by allocating some memory to a char pointer. I understand that this function is probably waaaaay sub-optimal for what it is trying to do, but what I really want to know is: 1. Can you normally initialise an array using a variable to declare the length like: char trimmed[len]; ? 2. If I had an array that was of that type (char trimmed[]) would it have the same return type as a pointer to char (ie char*). 3. If I make my array by callocing some memory and allocating it to a char pointer, how do I free this memory. It seems to me that once I have returned this array, I can't access it to free it as it is a local variable. Many thanks in advance Joe

    Read the article

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