小编kap*_*pil的帖子

如何在 C++ 中编写类库,就像我们为函数编写的那样

假设我们需要编写一个我们打算在我们的程序中使用的函数库,那么我们可以通过以下方式编写它。

在 .h 文件中,我们声明函数(mylibrary 可以是我们希望的任何文件名)假设 sum 是我们希望在我们的库中拥有的函数

int sum(int x, int y);
Run Code Online (Sandbox Code Playgroud)

然后我们将有一个 .cpp 文件,它将定义如下函数:

#include "mylibrary.h"

int sum(int x, int y){ return x+y; }
Run Code Online (Sandbox Code Playgroud)

现在我们希望在我们的程序中使用这个函数,比如 myprog.cpp,我们可以这样使用:

#include
#include "mylibrary.h"

int main()
{
cout<<sum(10,20)<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我们可以像对函数那样对类做类似的事情,即

我们可以在 .h 文件中声明类,例如:

class X;
class Y;
Run Code Online (Sandbox Code Playgroud)

然后在 .cpp 中定义类,如:

#include"myclasses.h"
class X
{
public:
int m;
};

class Y
{
public:
int n;
};
Run Code Online (Sandbox Code Playgroud)

然后在我们的程序中使用这些类,比如 myprog.cpp,像这样:

#include"myclasses.h"

int main()
{
class X myX;
myX.m = 0;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我试过了,得到了错误聚合“X myX”的类型不完整,无法定义。 …

c++ class static-libraries

2
推荐指数
1
解决办法
1万
查看次数

是否可以编写有助于复制初始化的显式构造函数?

我实际上正在编写字符串的实现,并且在尝试从单个字符构造字符串时面临着令人困惑的情况.

mystring.h

  class string final {
    private:
      static constexpr std::size_t default_capacity_ = 0;
      std::size_t current_capacity_;
      std::size_t sz_;
      std::unique_ptr<char[]> ptr_;
    public:
      explicit string(char);  // [1]
      string();
      string(const string&);
      string(string&&) noexcept;
      string(const char*);  // Undefined behavior if the input parameter is nullptr.
      ~string() noexcept;
  };
Run Code Online (Sandbox Code Playgroud)

mystring.cpp

  string::string(char ch) {
    sz_ = 1;
    current_capacity_ = get_appropriate_capacity(sz_);
    ptr_ = std::make_unique<char[]>(current_capacity_ + 1);
    ptr_.get()[0] = ch;
    ptr_.get()[1] = '\0';
  }

  string::string(const char* c_string) {    // [2]
    sz_ = std::strlen(c_string);
    current_capacity_ = get_appropriate_capacity(sz_);
    ptr_ = std::make_unique<char[]>(current_capacity_ …
Run Code Online (Sandbox Code Playgroud)

c++ string compiler-errors c++11

1
推荐指数
1
解决办法
45
查看次数

标签 统计

c++ ×2

c++11 ×1

class ×1

compiler-errors ×1

static-libraries ×1

string ×1