Precautions for the use of struct in c++

  • 2020-05-09 18:51:49
  • OfStack

1.C++ structure variables can be omitted when declaring struct, which is not allowed in c, as shown below


#include<iostream>
#include<string>
using namespace std;

struct test{
  int num;
  string name;
};

int main(void)
{
  test t;
  t.num=1;
  t.name="jack";
  cout<<t.num<<" "<<t.name<<endl;    
}

2. The structure declaration of c++ can be declared in the main () function, or before the main () function. Before that, the entire program can be called, which is the most common method. Internally, it can only be used within functions, which means it can be used within declared functions, similar to the concept of local variables. The following


int main(void)
{
  struct test{
    int num;
  };
  
  test hello;//right
  
}

void t()
{
  test t; //wrong
}


Related articles: