Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
<pre>static vector<Campfire> campfires;

class Campfire
{
public:
    int lifeSpan;
    future<void> thread;

    Campfire(int _lifeSpan)
    {
        lifeSpan = _lifeSpan;
    }

    void Enable()
    {
        while (lifeSpan > 0)
        {
            Sleep(1000);
            lifeSpan--;
            cout << "Campfire Life Span: " << lifeSpan << endl;
        }
        Campfire *campfire = this;
        campfires.erase(campfire);
        delete(this);
    }

    ~Campfire()
    {
        cout << "Campfire has expired" << endl;
    }
};



Also for async, is there a way to include a call back function to run when the code completes executing?

C++
async(launch::async, &Campfire::Enable, freshCampfire);


What I have tried:

So I'm assuming the error:

Severity Code Description Project File Line Suppression State Error C2065 'Campfire': undeclared identifier

is due to sequencing issue, I've Campfire Class below the vector of Campfires. What would the best way to get my Campfire class to access the global vector of Campfire "Campfires"?
Posted
Updated 6-Jun-21 3:42am
v2
Comments
James Irene 6-Jun-21 16:22pm    
for (i=2; i<=14; i+=3) result++
if(i>13) result += 100

Declare the static vector AFTER the class definition. The compiler DONT know it before it is declared.

Normally such static vars are a sign of bad coding style. So try some other solution. ;-)
 
Share this answer
 
Multiple problems here, and most are related to basic concepts that you break.

As a core rule, your main program should 'own' all objects that you need over the full lifetime of your program. In other words, rather than creating a global vector, declare it inside your main function.

Next, any function should only use and access members of its own class instance, objects that are passed to it as function arguments, or those it creates locally. The latter should not outlive the function call. In your case, the Camfire vector should be passed to the function as argument if that function is supposed to access it.

Last, always separate function definitions into declarations and implementations. In your case, change the class definition to just contain the declarations, then declare the Campfire vector, then add the implementations of your functions. That will resolve the cyclic dependency of the vector declaration with your class definition.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900