【问题标题】:C++ new operator is giving errorC++ new 运算符给出错误
【发布时间】:2015-02-13 04:40:19
【问题描述】:

在下面的代码中,语句“s= new int[50];”报错。

错误: 错误1 error LNK2001: unresolved external symbol "private: static int * Instack::s" (?s@Instack@@0PAHA) Stack.obj stack_pr

错误 2 错误 LNK2001: 无法解析的外部符号 "private: static int Instack::top1" (?top1@Instack@@0HA) Stack.obj stack_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();

}

【问题讨论】:

  • 你的堆栈中的所有变量都是静态的(在实例之间共享)——一旦你解决了你的链接器问题,它就不会像你想要的那样工作

标签: c++


【解决方案1】:

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

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

不幸的是,这会泄漏内存。您可能打算将stop 作为非静态成员变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2013-06-05
    • 2021-04-18
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多