В CPP, почему инициализация в классе действительна, но не назначение [дублировать]C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 В CPP, почему инициализация в классе действительна, но не назначение [дублировать]

Сообщение Anonymous »

Возьмите следующие классы, например: < /p>
class Test
{
public:
int a=1;// no errror
};
< /code>
class Test
{
public:
int a;
a=1; // error
};
< /code>
Here the second case gives error. After a few searches the reason i found is that because class only allows declaration and no assignment as class is just supposed to be a blueprint with no run time scope and assignment would require it to have run time scope as it requires a value being placed in a certain memory location, which is done at run time. But this explanation further confused me, now i am left with two more question:
  • Is initialization also a declaration?
  • How is initialization different from assignment, in the sense that assignment also requires putting certain value in the memory location assigned to a variable and initialization also does the same, then how are they different? I know that that they are different syntactically i.e only statements of the form:
int a=1;
< /code>
are considered assignment and statements of the form:
int a;
a=1;
< /code>
are considered assignment, but aren't they the same thing fundamentally i.e putting certain value in memory assigned for a variable? Then why is one valid and the other not valid? There is a similar question trying to ask difference between initialization and assignment but answers and comments to it don't explain why initialization is allowed in a class but assignment is not allowed even though both are fundamentally putting certain value in memory assigned for a variable.
Any help is appreciated. Thanks in advance!!

Подробнее здесь: https://stackoverflow.com/questions/795 ... assignment
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»