c++ private:变量引用另一个类[重复]

vbkedwbf  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(67)

此问题在此处已有答案

Implementation file (.cpp) for a class with member initialization(2个答案)
C++11 member initializer list vs in-class initializer?(3个答案)
Constructor initializer list vs initializing in the header file(1个答案)
How to separate a class and its member functions into header and source files(8个答案)
昨天就关门了。
我是一个初学者与C++和我已经寻找答案,找不到它。
我正在写一个类,下面是我认为与我遇到的问题相关的部分的净化版本:

File: MyClass.h
class MyClass {
   private:
      AnotherClass  xyz;
}

File MyClass.cpp
MyClass :: MyClass() {
    AnotherClass xyz(1,2,3);
}
MyClass :: foo() {
    xyz.something();
}

字符串
基本上,“MyClass”需要一个对“AnotherClass”的引用,以便在自身内部使用。我不知道如何在头文件中定义它,然后在构造函数中初始化它。
如果这能增加一些清晰度的话,我会用Java编写如下代码(无需检查):

class MyClass() {
   private AnotherClass xyz;
   public MyClass() {
      xyz = AnotherClass(1,2,3);
   }
   public void foo() {
      this.xyz.something();
   }


}

dauxcl2d

dauxcl2d1#

你几乎已经做到了;你需要初始化成员变量而不是声明另一个。
File:Zhongnanhai.jpg

#include "AnotherClass.hpp"

class MyClass {
   private:
      AnotherClass  xyz;
}

字符串
文件MyClass.cpp

#include "MyClass.hpp"

MyClass::MyClass() :
xyz(1,2,3)
{}

MyClass::foo() {
    xyz.something();
}

相关问题