【问题标题】:Static Object of a class in another class in aggregation relationship C++聚合关系C ++中另一个类中的一个类的静态对象
【发布时间】:2019-12-12 20:07:07
【问题描述】:

我有两个类,第一个类包含另一个类的静态对象,但 C++ 不允许我这样做并给我一些错误。

source.cpp

#include"control.h"

int main()
{
  Controller cnt;
  cnt.tempcont();
  return 0;
}

控制.h

#include"recorder.h"

class Controller 
{
public:
  static recorder rec;
  void tempcont();
};

recorder Controller::rec;

控制.cpp

#include"control.h"

void Controller::tempcont()
{
  rec.temprec();
}

recorder.h

#include<iostream>

using namespace std;

class recorder
{
public:
  int a;
  void temprec();
};

recorder.cpp

#include"recorder.h"

void recorder::temprec()
{
  cout << "temp rec called";
}

我收到以下错误,我不知道为什么会出现这些错误..

错误 LNK1169 发现一个或多个多重定义符号

错误 LNK2005 "public: static class recorder Controller::rec" (?rec@Controller@@2Vrecorder@@A) 已在 control.obj 中定义

【问题讨论】:

    标签: oop c++11 static aggregation


    【解决方案1】:

    您在头文件中定义变量Controller::rec。这意味着该变量将在包含该头文件的每个translation unit 中定义。它只能在一个翻译单元中定义。

    这很容易做到:只需将定义移动到一个单个源文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2017-03-17
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2019-12-03
      • 2023-04-10
      相关资源
      最近更新 更多