【问题标题】:c++ multiple classes with identical methods which use 'this' inc++ 具有相同方法的多个类,其中使用'this'
【发布时间】:2022-01-15 19:06:20
【问题描述】:

我需要 oop 方面的建议。 所以基本上我有几个类具有相同的方法,但在这个方法中使用了this 关键字。

我尝试了继承,我发现我可以像这样访问派生类的thisstatic_cast<derived *>(this),但据我所知,这被认为是一种不好的做法。这是带有推导的代码:

template <typename T>
class Base {
public:
    void add(string filename) {
        ofstream file;
        file.open(filename, ios::app);
        file.write((char*)static_cast<T*>(this), sizeof(*static_cast<T*>(this)));
        file.close();
    }
};

class Product : public Base<Product> {
public:
    char id[11];
    char name[50];
    char price[9];
    char stock[9];
};

这是课程:

class Product {
public:
    char id[11];
    char name[50];
    char price[9];
    char stock[9];

public:
    void add(string filename) {
        ofstream file;
        file.open(filename, ios::app);
        file.write((char*)this, sizeof(*this));
        file.close();
    }
};

我还有其他几个类似的类,它们都有相同的add() 方法。而且我想知道在没有代码重复的情况下最好的方法是什么,或者在可读性和类似的东西方面使用代码重复更好?

【问题讨论】:

  • 如果您了解强制转换有时是一种不好的做法,那么您对(char*)this 中的 C 风格强制转换有何看法?顺便说一句:你的代码甚至没有派生,所以我不明白你的问题。
  • 嗨@UlrichEckhardt,我最近了解到强制转换是一种不好的做法,而且我在编写您提到的代码时并不知道这一点。感谢您指出我也会解决这个问题。
  • 至于派生,我只是想知道在多个类中具有相同方法但其中使用this 关键字的情况下,最佳实践是什么。
  • 所提供的代码没有以问题询问的方式使用static_cast。我怀疑问题在于add 函数正在做两个 的事情,但实际上应该做一个 的事情。将该方法重构和分解为两个单独的方法,然后使用虚拟成员函数的编写方法可能会解决问题并成为问题的解决方案。
  • 将对象作为原始 blob 写出需要 static_assert(std::is_trivial&lt;Product&gt;::value);static_assert(std::is_standard_layout&lt;Product&gt;::value);,它们会传入给定的代码,但随着代码的发展,可能很容易且无意中失败。值得添加断言,或者最好不要写成原始 blob(但那是你的电话)。

标签: c++ oop


【解决方案1】:

您所做的称为序列化。您可能需要像 libnop 这样的库。谷歌“C++ 序列化库”的其他选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多