【问题标题】:Trying to use static class variable to create new ID for objects尝试使用静态类变量为对象创建新 ID
【发布时间】:2015-02-05 04:34:53
【问题描述】:

我是 C++ 新手,当我尝试运行此程序时,它告诉我:“错误 LNK2001:无法解析的外部符号“私有:静态 int Plate::plate_nID”。我现在只是尝试创建板类和打印出身份证。不知道哪里出错了。

#pragma once
#include <string>

using namespace std;

class Plate{
   private:
      int id;
      string plateName;
      static int plate_nID;

      int generateID(){
         plate_nID++;
         return plate_nID;
      }
   public:
      Plate(string name){
         plateName = name;
         id = generateID();
      }
      ~Plate(){}
      int getID(){
         return id;
      }
      string getName(){
         return plateName;
      }
};

这是我的主要内容:

#include "Plate.cpp"
#include "PlateNode.cpp"
using namespace std;

int main(){
Plate s=Plate::Plate("p1");
cout << s.getID();}

我看过这个问题: Undefined reference to static class member 与我的类似问题被标记为重复,但是当我尝试这样做时,它告诉我:不能在类之外实例化非静态成员。请帮忙!

【问题讨论】:

  • 或者在函数generateID 中将plate_nID 设为静态(其本身应该是静态的)
  • 考虑Plate(const string&amp; name)和const string&amp; getName() const

标签: c++


【解决方案1】:

你需要在你的类之外定义静态变量,只有这样你的代码才能工作

int Plate::plate_nID = 0;

你必须在类之外定义它(最好在 main() 之外)

在课后立即定义它可能会更好。

【讨论】:

    【解决方案2】:

    你需要在类外定义static成员变量。大致如下:

    int Plate::plate_nID = 0;
    

    【讨论】:

    • @ChrisMurphy,它必须在类之外,在 .cpp 文件中。
    • 我试图把它放在 Plate.cpp 文件中,但是当我尝试在主文件中实例化一个板时,它说 plate_nID 已经定义
    • 您不应该在另一个 .cpp 文件中 #include 一个 .cpp 文件。 #include 仅 .h 文件。分别编译 .cpp 文件并链接生成的目标文件以创建可执行文件。
    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2012-10-31
    相关资源
    最近更新 更多