在尝试使用其他OO语言编程多年之后,我试图学习c++。

我试图为另一个类创建一个包装器类,但是很难弄清楚如何正确地设置它。

例如,具有以下内容...

main.cpp

#include "foo.cpp"
#include <iostream>

int main() {
  Foo foo(42);
  std::cout << foo.get_barx() << std::endl;
  return 0;
}

foo.cpp
#include "bar.cpp"

class Foo {
  public:
    // I'm trying to declare the member variable `m_bar` here.  I
    //   don't want to be instantiating an instance of Bar yet,
    //   but I think that might be exactly what's happening.
    Bar m_bar;

    Foo(int y) {
      // Here's where I really want to instantiate an instance of Bar
      //   and assign it to m_bar.
      Bar m_bar(y*2);
    }

    int get_barx() {
      return m_bar.getx();
    }
};

bar.cpp
class Bar {
  public:
    int m_x;

    // I seem to need this default constructor for the declaration
    //   of `m_bar` above, but I don't think that line should be
    //   calling any constructors.
    Bar() { m_x = 21; };

    Bar(int x) {
      m_x = x;
    }

    int getx() {
      return m_x;
    }
};

当我编译并运行它时,我得到21,但我希望是84。我很确定我做的事情根本上是错误的,而且我很确定这与我声明m_bar成员的方式有关Foo中的变量,但我不知道完成此操作的正确方法。

最佳答案

main.cpp

#include "foo.cpp"
#include <iostream>

int main()
{
    Foo foo(42);
    std::cout << foo.get_barx() << std::endl;

    return 0;
}

在这里,您应该包含一个 header (例如,将“foo.cpp”重命名为“foo.h”)。通常, header 提供声明,而源(例如.cpp文件)提供定义/实现。

Bar.cpp(再次应为 header )
class Bar
{
public:
    int m_x;

    // A default constructor is not required, however defining any constructor
    // prevents auto generation of the default constructor

    Bar(int x) : // This starts the initializer list section
        m_x(x)
    {
        // This is assignment not initialization
        // m_x = x;
    }

    // See the trailing 'const', research const correctness
    int getx() const
    {
        return m_x;
    }
};

foo.cpp(再次应为 header )
#include "bar.cpp"

class Foo
{
public:
    // Just declaring a `Bar` data member
    Bar m_bar;

    Foo(int y) :
        m_bar(y) // Initialize `Bar` data member using the available constructor
    {
        // First, this declares a new `Bar` instance which is different than
        // the class member, regardless of the fact they are named the same
        // Bar m_bar(y*2);

        // Furthermore, even if you did the following it is assignment not initialization
        // m_bar = Bar(y*2);

        // Since initialization already occurred before this point an error
        // will result if the `Bar` data member isn't instantiated via the
        // only available constructor, since there isn't a default constructor as
        // explained above
    }

    // Same comment about const correctness
    int get_barx() const
    {
        return m_bar.getx();
    }
};

关于c++ - 如何包装另一个类(C++),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32833774/

10-11 23:14
查看更多