What Could Cause an Assignment to Not Work

What could cause an assignment to not work?

Is MyEnum.TYPE_OF_ENUM the first value in the enum, or is TYPE_OF_ENUM assigned to a integer value of 0?

A non-initialized enum will be set to 0, so it may already match.

Otherwise, it is much more likely that you have something else going on that you haven't noticed yet.

Why does assignment operator not work as expected?

I see several issues with this code:

  • pop is not being initialized in the default constructor (which you are not calling, but you should still implement it properly, if you are going to implement it manually at all).

  • operator= is not updating the value of this->pop at all, which is the root cause of your issue. If you declare operator=, you are responsible for implementing it properly yourself, the compiler will not help you at all. But if you do not declare operator=, the compiler will auto-generate a default implementation that will assign a copy of the pop value for you.

  • operator<< should be taking the TestClass parameter by const reference.

Try this:

#include <iostream>

class TestClass{
private:
int pop;
public:
TestClass() : pop(0) { // <-- add this value!
std::cout << "Default Constructor\n";
}

TestClass(int i) : pop(i) {
std::cout << "Param Constructor\n";
}

TestClass& operator=(const TestClass &other){
std::cout << "Assignment Operator\n";
pop = other.pop; // <-- add this!
return *this;
}

friend std::ostream& operator<<(std::ostream &out, const TestClass &x);
};

std::ostream& operator<<(std::ostream &out, const TestClass &x){
out << " This is the TestClass with pop=" << x.pop << "\n";
return out;
}

int main()
{
TestClass P0(333);
TestClass P_foo(555);

P_foo = P0; // <-- this will work as expected now

std::cout << P0;
std::cout << P_foo;

return 0;
}

Assignment to DataFrame not working but dtypes changed

if I understand your question correctly, then your problem starts when you create empty_numpy matrix.
My favourite solution would be to use empty_numpy = np.empty([5,5]) instead (default dtypes is float64 here). Then the "Result of first try: " is correct. It means:

import pandas as pd
import numpy as np

dataset = [[[i for i in range(5)],] for i in range(5)]
dataset = pd.DataFrame(dataset, columns=['test'])

empty_numpy = np.empty([5,5])
# here you may add empty_numpy.fill(np.nan) but it's not necessary,result is the same

empty_frame = pd.DataFrame(empty_numpy, columns=[str(i) for i in range(5)])

series = dataset['test']
target_frame = pd.DataFrame(list(series))

# following assignment is correct then
empty_frame[:] = target_frame
print('='*40)
print(f'Data types of empty_frame: {empty_frame.dtypes}')
print('='*40)

print("Result of first try: ")
print(empty_frame)
print("="*40)

Or just add dtype attribute to your np.arrange call, just like this:

empty_numpy = np.arange(25, dtype=float).reshape(5, 5)

Then it works too (but it's a little boring ;o).

When does := work not as an assignment operator?

In Object Pascal := is always an assignment operator.

The documentation wording is perhaps misleading in this respect. It does not mean that this operator sometimes does something else, only that the operator is sometimes referred to as the assignment operator.

The distinction is the same as when I say that I sometimes refer to my female parent as 'mother'. She is always my mother but sometimes I call her "mum" or "granny" (when talking to my children) or using her name. But she is always my mother. I just don't always refer to her using that precise term.

Also be aware that there are some occasions when assignment is achieved using a simple = symbol. For example, identifying default parameter values:

procedure SomeUsefulProc(const aSwitch: Boolean = FALSE);

Also, when declaring constants or initialising global variables:

const
DEFAULT_PREFIX = 'PFX';

var
gMeaningOfLife: Integer = 42;

However, this does not alter the fact that := is the assignment operator.

The assignments in these other cases = are not "operations" in code, but declarations.

Properties vs Variables

The confusion in your question arises not from a difference in the meaning of the := symbol, but rather in the fact that your first example involves a variable where-as the second involves a property of an object.

Objects may declare properties where the assignment of a value to a property actually calls a procedure to apply the new value. The TStringList is a good example.

After adding an item to a string list, that list has an item that may be accessed using the index of that item in the Strings property:

stringList.Add('a');

// stringList.Strings[0] has the value 'a'

The Strings property is declared as the default property of the TStringList class meaning that if an "array" style index is used without any property name, then this Strings property will be assumed by default.

i.e. these two lines of code are exactly equivalent:

s := stringList.Strings[0];
s := stringList[0];

The Strings property is implemented using a function to retrieve the value of specific items (Get) and a procedure to modify them (Put). The above lines of code are equivalent to using the Get function with 0 as the parameter:

s := stringList.Get(0);

Since the Strings property is declared with a write accessor then you can also write to this property, thereby calling the Put procedure. To write to a property you assign a value to it, using ... the assignment operator. In this case, the array index of the property is passed to the procedure along with the value to be assigned.

As before, since the Strings property is the default property for a stringlist, the following two lines of code are exactly equivalent:

stringList[0]         := 'b';
stringList.Strings[0] := 'b';

And in both cases the effect is to result in a call to the write procedure for the Strings property:

stringList.Put(0, 'b');

The operator is still the assignment operator and we still say that we have "assigned a value" to the property. Assignment, in code (as opposed to in a declaration), is always performed using the assignment operator:

aVariable            := value;
aObject.SomeProperty := value;

The difference is that in the case of an object property the response to that assignment is dependent upon the implementation of the property involved. It may simply modify some value on the object directly, or it may call a procedure to first validate the value being assigned or perform some more complex response to that property change.

In the case of a TStringList for example, changing an item in the list not only modifies that item but also triggers a change notification event.

Records vs Objects (or Values vs References)

In more recent versions of Delphi you may also have properties with read/write functions implemented by record types. These follow the same implementation pattern as properties on objects (i.e. classes). However, in that case you will observe very different results since a record is a value type, not a reference type.

NOTE: For the examples that follow for simplicity I am using a property that simply directly reads and writes the member rather than using Get/Set functions, but the principle is the same and also applies even if a member of an object is exposed directly (i.e. without an explicit property declaration).

If TMyData is implemented as a class then the variables a and b are references to an instance of that class. This must be explicitly created and when we assign one to the other all we are doing is creating a duplicate reference to the same object:

type
TMyData = class
private
fName: String;
public
Age: Integer; // Directly exposed member - effectively a read/write property
property Name: String read fName write fName;
end;

var
a: TMyData;
b: TMyData;
begin
a := TMyDate.Create; // Create an object and store a reference in a
try
a.Name := 'foo'; // Set the name and age of the object we just created
a.Age := 42;

b := a; // b now also REFERENCES the same object as a
// a.Name = 'foo' / Age = 42
// b.Name = 'foo' / Age = 42

b.Name := 'bar'; // We changed the Name of the object to 'bar'.
// a.Name = 'bar' / Age = 42
// b.Name = 'bar' / Age = 42
// a = b (they reference the same object)
finally
a.Free; // both a and b references are now invalid (the object has been destroyed)
end;

If TMyData is instead implemented as a record then a significant difference is introduced. There is no longer any need to explicitly create or destroy objects, and when we assign values of this record type, we create copies of the value involved rather than a reference to it:

type
TMyData = record
private
fName: String;
public
Age: Integer; // Directly exposed member - effectively a read/write property
property Name: String read fName write fName;
end;

In this case if we have two variables of this type then right from the start we have two separate TMyData records and when we assign one to the other, we are copying the entire TMyData value:

var
a: TMyData;
b: TMyData;
begin
// a and b are both new, initialised records:
// a.Name = '' / Age = 0
// b.Name = '' / Age = 0

a.Name := 'foo'; // We have set the Name and age of a. b is unchanged
a.Age := 42; // a.Name = 'foo' / Age = 42
// b.Name = '' / Age = 0

b := a; // b is now a COPY of a.
// a.Name = 'foo' / Age = 42
// b.Name = 'foo' / Age = 42

b.Name := 'bar'; // We changed the Name and age of b.
b.Age := 84; // a.Name = 'foo' / Age = 42
// b.Name = 'bar' / Age = 84

end;

assignments are not expressions, and only expressions are allowed in this context --- how to resolve this error

An expression is something that evaluates to a value. An assignment is something that assigns a value to a variable or property.

x *= y is an assignment that is shorthand for x = x * y.

You cannot return an assignment, because it does not evaluate to a value. An assignment contains an expression on the right side of the equals sign, but as a whole does not represent an expression.

There are some other syntax problems you have. You can't modify a function paramter's value (num2-- isn't allowed).

The logic also doesn't make sense. return returns an expression immediately. To fix your code, you need to create a local variable from num2, and move the return statement to the end.

fun power(num1 : Int, num2: Int): Int {
var result = 1
var count = num2
while (count != 0) {
result *= num1
count--
}
return result
}

FYI, there's a function called repeat that is simpler than using a while loop with a counter. It runs the code inside the brackets by the number of times you give.

fun power(num1 : Int, num2: Int): Int {
var result = 1
repeat(num2) {
result *= num1
}
return result
}

Onclick function assignment not working

Try this:

document.getElementsByTagName("body ").addEventListener("click", function(){
gameOver();
});
function gameOver() {
alert("Game Over!");
}

Android - TextView assignment is not working as expected

private void ProcessNumbers()
{
TextView textViewProcessNumbers = (TextView) findViewById(R.id.textViewProcessNumbers);
textViewProcessNumbers.setText("Processing...");
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 30000ms
textViewProcessNumbers.setText("Processed...");
}
}, 30000);
}

Use handler for delay. Hope it helps



Related Topics



Leave a reply



Submit