c ++中的静态构造函数和致命错误LNK1120:1个未解析的外部 [英] Static constructor in c++ and fatal error LNK1120: 1 unresolved externals

查看:251
本文介绍了c ++中的静态构造函数和致命错误LNK1120:1个未解析的外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我应该让你知道,我不是一个程序员,我只是这样做一个家庭作业,所以如果可能,我会需要一个真正详细的解释:)

To start with i should probably let you know that i am by no means a programmer, and i'm just doing this for a homework assignment, so if it's possible i will require a really detailed explanation :)

我当前有一个Node类,用来存储点的坐标。除此之外,我想要做的是根据计数器为每个不同的Node对象分配一个索引号。从我从互联网上收集的方式,我这样做是通过使用另一个类,它在构造函数中初始化我的计数器,在Node类中,我只是将它添加为静态参数。

I currently have a Node class which i use to store the coordinates of points. Besides that, what i want to do with it is assign each different Node object an index number based on a counter. From what i gathered off the internet the way i do this is by using another class which initializes my counter in the constructor, and inside the Node class i just add it as a static parameter.

这是我上面的代码:

class counter
{
  public:
    int nr;
    counter()
    {
        nr = 0;
    }
};

class Nod   
{  
  static counter ctr;

  public:   
     int index;      
     Punct pct;
     Nod(Punct &temp)
     {  
         pct = temp;    
         index = ctr.nr ++ ;
     }
     Nod() {}   
}; 

现在,构建确定,但是一旦我尝试声明一个Nod对象在我的主要功能我得到以下错误:致命错误LNK1120:1未解决的外部,我绝对没有线索为什么这是。我以前遇到这个错误,当我试图写我自己的析构函数,但我通过删除该位的代码。

Now, that builds ok, but as soon as i try to declare a Nod object inside my main function i get the following error: fatal error LNK1120: 1 unresolved externals and i've got absolutely no clue as to why this is. I've previously gotten this error when trying to write my own destructor but i got around that by just deleting that bit of code.

谢谢你,对不起,如果我'

Thank you, and sorry if i'm using the wrong terminology for some of the things i've referred to.

推荐答案

我以前也犯了这个错误的术语。然后我读了Scott Meyers的一篇文章。他推荐一个函数static,而不是类静态变量。这意味着你在一个地方声明和定义一个变量。以下列印:

I used to fall foul of that too. Then I read an article by Scott Meyers. He recommended a function static, rather than class static variable. This means you declare and define a variable all in one place. The following prints:


0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9



#include <iostream>

int next_index(void)
{
  static int index = 0;
  return index++;
}

int main(void)
{
  for (int i = 0; i < 10; ++i) {
    std::cout << next_index() << ' ';
  }
}

在您的情况下,

Nod(Punct &temp)
 {  
     pct = temp;    
     index = next_index();
 }

这篇关于c ++中的静态构造函数和致命错误LNK1120:1个未解析的外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆