#include "stdafx.h"
#include <iostream>
usingnamespace std;
class test{
public:
void init(int);
int n;
int *p;
p=newint[n];
};
void test::init(int a)
{
n=a;
}
int main(void)
{
int a;
cout<<"a="; cin>>a;
test var;
var.init(a);
cin>>a;
return 0;
}
I want to read in main() a value for a, then passing it to the class and dynamic allocation an int array *p, with size a. Thank you in advance, i really need to know how to do this.
I think you suffered a mental model misapprehension1 about defining C++ classes. As a rule of thumb, inside the class definition goes information about the class; what kind of objects it has inside it, what kinds of functions. Any code that is to be actually executed goes inside functions.
This follows from the principle that the class definition is a description of the class - it's not actually code that gets executed. When you create an object of that class, then some code is executed and new objects created. As such, putting code to be executed (p=newint[n];) in the description of the class makes no sense.
C++ 11, typically, trashes that mental model with a few conveniences, but that's C++11 for you :p