errore:il membro di dati statici non const deve essere inizializzato non in linea

errore:il membro di dati statici non const deve essere inizializzato non in linea


class Solution {
public:
static int m=INT_MIN; // it shows error: non-const static data member must
be initialized out of line.(why?)
using "int m=INT_MIN" is fine.
int func(TreeNode*root){
if(root==NULL){
return 0;
}
int l=max(func(root->left),0);
int r=max(func(root->right),0);
m=max(l+r+root->val,m);
return max(l,r)+root->val;
}
int maxPathSum(TreeNode* root) {
if(root==NULL)
{
return 0;
}
m=INT_MIN;
int x=func(root);
return m;
}
};

Devo aggiornare il valore della variabile m . Pertanto sto usando static int tipo di dati. Ma viene visualizzato il seguente errore.
Utilizzo di int invece di static int sta funzionando bene. Ma perché static int dando errore?



Alcune risposte al codice


class Solution {
public:
static int m=INT_MIN;
// it shows error: non-const static data member must
be initialized out of line.(why?)
using "int m=INT_MIN" is fine.
int func(TreeNode*root){
if(root==NULL){ return 0;
}
int l=max(func(root->left),0);
int r=max(func(root->right),0);
m=max(l+r+root->val,m);
return max(l,r)+root->val;
}
int maxPathSum(TreeNode* root) {
if(root==NULL)
{
return 0;
}
m=INT_MIN;
int x=func(root);
return m;
} };
class Solution {   public:
int m = INT_MIN;
};
class Solution {   public:
static int m = INT_MIN;
};
#include <iostream>
enum ArgCase1 { Case1 };
enum ArgCase2 { Case2 };
class Solution { public:
int m = 123;
Solution() = default;
// will use m(123) implicitly
Solution(ArgCase1) { } // will use m(123) implicitly
Solution(ArgCase2): m(456) { } // default of m ignored };
#define DEBUG(...) std::cout <<
#__VA_ARGS__ <<
";\n";
__VA_ARGS__ int main() { DEBUG(Solution sol);
std::cout <<
"sol.m: "
<<
sol.m <<
'\n';
DEBUG(Solution sol1(Case1));
std::cout <<
"sol1.m: "
<<
sol1.m <<
'\n';
DEBUG(Solution sol2(Case2));
std::cout <<
"sol2.m: "
<<
sol2.m <<
'\n';
}
Solution sol;
sol.m: 123 Solution sol1(Case1);
sol1.m: 123 Solution sol2(Case2);
sol2.m: 456
#ifndef SOLUTION_H #define SOLUTION_H  class Solution {   public:
static int m;
};
#endif // SOLUTION_H
// header of this module: #include "solution.h"
int Solution::m = 123;
#ifndef SOLUTION_H #define SOLUTION_H  class Solution {   public:
inline static int m = 123;
};
#endif // SOLUTION_H