Sorry to say this, but your code is more confused than anyone here has told you. Please don't be offended. Just listen and learn.
First off, your naming stinks.
newinstance isn't a "new instance" of anything. Specifically, it doesn't tell you anything about the variable. A better name would be something that describes the
meaning of the number sequence, like
monthly_rainfall_in_inches or
vernam_cipher_key or
weekly_bonus_points. Likewise,
a is a non-name -- it doesn't tell you anything.
Second, and you don't have to worry too much about this now (you'll learn better later), but you are abusing levels of abstraction. Don't name your function
foreach(). That has a very standard meaning which does not exactly match what you are trying to do. Again, be more specific. Use the standard
assign() or
operator=() or just name it something specific, like
initialize_with_array().
Third, you are missing variable scope. Line 9 declares a
local variable -- local to the
for loop. Each time through the loop you create a
T, assign it a value, and then destroy it. When your function terminates you create and return another
T with value zero.
Essentially, there is never more than one instance of a
T (not counting any copy that
may exist when
returning). This isn't an array, because you cannot recall what previous elements in the sequence were -- you never save any!
If you stick to a standard
vector (or
deque or
list), your program could look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int INITIAL_PRIMES[] = {2,3,5,7,11,13,17,21,23};
vector <int> primes(
INITIAL_PRIMES,
INITIAL_PRIMES + (sizeof(INITIAL_PRIMES) / sizeof(INITIAL_PRIMES[0]))
);
cout << "prime numbers:\n";
for (unsigned n = 0; n < primes.size(); n++)
cout << primes[n] << endl;
return 0;
}
|
This, however, is not what I think you are trying to do.
What exactly are you trying to accomplish? Perhaps we can steer you better.