C++新运算符出现错误

C++ new operator is giving error

本文关键字:错误 运算符 C++      更新时间:2023-10-16

在下面的代码中,语句"s=new int[50];"出现错误。

错误:错误1错误LNK2001:未解析的外部符号"private:static int*Instack::s"(?s@Instack@@0PAHA)Stack.obj Stack_pr

错误2错误LNK2001:未解析的外部符号"private:static int Instack::top1"(?top1@Instack@@0HA)堆栈.obj堆栈_pr

错误3致命错误LNK1120:2个未解析的外部文件C:\Users\vinoda.kamble.LGE\Desktop\Bill\New folder\stack_pr\Debug\stack_pr.exe stack_pr

#include<iostream>
#include<stdlib.h>
#define maxma 50;
using namespace std;
class Instack{
private: 
static int *s;
static int top1;
public:
Instack ()
{
    s= new int[50];
}
void Instack:: push(int t)
{
    s[top1++]= t;
}

int Instack::pop()
{
    int t;
t= s[--top1];
return t;
}
};

void main ()
{
    Instack S1,S2;
S1.push(522);
S2.push(255);

cout<<"S1 pop",S1.pop();
cout<<"S2 pop",S2.pop();
}

原因是静态类成员需要一个定义。在类定义之外添加这样的内容将解决链接问题。

int* Instack::s = nullptr;
int Instack::top;

不幸的是,这会泄露内存。您可能想要做的是将stop都作为非静态成员变量。