简体   繁体   中英

C++ Variable declaration of type class does not name a type?

Im having a problem involving declaring variables that are of a type class.

Example code

class Party{
     public:

     string partyName;
     Leader leader;
     Candidate candiate;
     nationalcompaignManager nationalManager;
     natioanlfinancialManager financialManager;
     compaignMananger newcompaignMananger; 
};

class Leader: public Person {

    public:
     int popularity;
     int totalcountryVotes;
}

As seen in this code snipit, there are several variables declared of a type of a class, in this example ive demonstrated how a class Leader does exist for a variable leader;

Error code example(as its the same for all)

 error: ‘Leader’ does not name a type
      Leader leader;

There are classes for each variable but for sake of simplicity I'll work with Leader. Leader is clearly defined as a class in the program scope, yet variables of its type are not? Im unsure as to why this error is occuring

Just declare Leader above Party to make it "visible" to Party class.

class Leader
{
};

class Party
{
  Leader leader;
};

C++ is a language of sequential nature which means that it starts compiling your code from top to bottom. So before you declare a class variable, you should first define that class before the declaration otherwise there is no existence (till it is defined) of the class and thus, resulting in an error.

class Leader
{
};   //The class Leader is now defined.
class Party
{
Leader leader;
};

In simple words, you cannot use something that hasn't been created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM