gpt4 book ai didi

c++ - 这是使用继承的好方法吗?

转载 作者:行者123 更新时间:2023-11-30 03:25:35 25 4
gpt4 key购买 nike

这是使用继承的好方法吗?

#include <iostream>

namespace Test::A {
class A {
char const * const this_message;

public:
constexpr A(char const * const message) noexcept
: this_message(message) {
}

constexpr char const * message() const noexcept {
return this_message;
}
};

struct B : public A {
constexpr B(char const * const message) noexcept
: A(message) {
}
};
}

int main() {

std::cout << sizeof(Test::A::A) << '\n';
std::cout << sizeof(Test::A::B) << '\n';

std::cout << Test::A::B("Test 1").message() << '\n';

try {

char const * const Test4 = "Test 4";

// Uncomment / comment to toggle between
//throw Test::A::B("Test 1");
throw Test::A::B(Test4);

} catch (Test::A::A const a) {
// I'm passing 'a' by copy because the size of 'a'
// will always be either 4 or 8 bytes / it's faster this way.
constexpr auto message = Test::A::B("Test 3").message();

std::cout << a.message() << " " << message << '\n';
}

return 0;
}

我有两个问题:

A) 这是使用继承和...的好方法吗

B) 这个程序是否正确、格式正确且没有未定义的行为?

我想创建我自己的简单的两级异常层次结构(只有一个基类和一些派生类),我正在尝试找到一种无需任何虚方法的方法。

下面的代码确实有效,它似乎以正确的顺序调用析构函数,即使在派生类上没有要析构的东西。然而,我对这项工作的内部结构有些困惑。

我知道如果我想通过派生类的基指针删除派生类,我需要一个虚拟析构函数,但我并没有考虑支持那种多态性。

我知道通过从 B 调用 message 方法,我只是从 A 调用方法,而后者又只返回成员变量this_message,可以在AB中初始化。

将对象传递给catch调用时,B对象是否通过切片过程变成了A?但是因为 B 只是初始化了 A 的一个成员/和 A 有相同的状态,所以最后一切都解决了。

这个想法是通过传递包含行号、文件位置等的静态字符数组在宏中初始化 A 类及其派生类。

最佳答案

I know that I need a virtual destructor if I wish to delete a derived class through its base pointer, but I'm not thinking about supporting that sort of polymorphism.

如果您是项目中唯一的程序员,那么这种妥协可能很实用,但您需要与每个加入该项目的人沟通并强制执行,因此您很难扩展或重用您编写的代码。

When passing the object to the catch call, is the B object turned into an A by the process of slicing? But because B just initializes a member of A / have the same state as A, it all works out in the end.

是的,通过切片。是的,它卡在一起。

The idea is for the A class and its derived classes to be initialized in a macro by passing a static char array containing line number, file location, etc.

这是另一个问题/陷阱:人们习惯于 std::exception 在内部 std::string 中捕获文本,因此其他程序员必须警告不要做像 Test::A::B(my_message_in_a_string.c_str());Test::A::B(my_ostringstream.str()) 这样的事情,这使得将有用的消息放入您的异常类变得更加困难。

A) Is this a good way of using inheritance and...

它允许您选择按基类(无论是通过引用还是切片)或派生类型进行捕获,因此继承增加了有用的功能。

B) Is this program correct, well formed and without undefined behaviour?

是的,但是由于缺乏虚函数和切片的使用,它在维护方面很脆弱并且难以扩展。

关于c++ - 这是使用继承的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com