gpt4 book ai didi

c++ - 就像在 python 中定义 __str__ 一样,在类上调用时如何覆盖 c++ 中的标准全局函数

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

主要问题:

在 python 中,我们可以在类中定义诸如 __unicode____str__ 之类的东西,这样当我们调用 print()str() 在一个类上(即 str(myclass)),我们得到一个定制的和可读的字符串表示。在 C++ 中,如何为类完成此操作?这样当我们调用 string(myclass) 时,我们得到 myclass 的字符串表示?

背景故事:

这可能会被标记为低质量问题,因为我是 C++ 的新手。

我目前正在练习 exercism.io 中的 C++ 练习,重点是编写代码以使提供的测试用例能够通过。我已经完成了 39 个可用练习中的 30 个,但是我目前还停留在这个特定的测试用例代码上:

const auto actual = string(date_independent::clock::at(t.hour, t.minute));

在前面的练习中,我将其理解为“创建一个名为date_independent 的命名空间,其中包含一个名为clock 的类,并使该类具有一个公共(public)的名为 at 的函数,它将接受两个参数(在本例中为 2 个整数小时和分钟)”。我将该函数设为 static 函数,因为测试代码并未真正实例化时钟对象。我还将返回值设为 std::string 类型。它适用于前几个测试用例。不幸的是,我随后遇到了这段测试代码:

const auto actual = string(date_independent::clock::at(a.hour, a.minute).plus(a.add));

在这种情况下,我之前返回字符串的解决方案适得其反,因为现在我需要对 at() 的返回值调用 plus() 函数。这显然无法完成,因为 at() 返回一个 std::string,并且字符串没有成员函数。那时我注意到有一个 string() 函数 (?) 封装了整个 date_independent::clock::at(a.hour, a.minute).plus(a.add )。但是我不确定这个 string() 函数是从哪里来的,以及我如何才能找到。对于 python,我假设这是某种类型转换为字符串,或其他一些名为字符串的函数。然而,这是 C++,我还没有遇到过这样的类型转换,所以也许不是这样。我的另一个想法是,类似于 python,也许类可以覆盖标准全局函数如何与它们一起工作。比如当 __unicode____str__ 在 python 类中定义时,打印语句可以返回自定义值。

所以我的问题再次是,我假设这个 string 函数应该是一个应该被覆盖的成员函数是否正确?如果是,如何在 C++ 中完成?如有任何回应,我将不胜感激。我很确定我没有看到一些基本的东西,因为我是这门语言的新手。

下面是测试代码的一些上下文。

...

BOOST_AUTO_TEST_CASE(time_tests)
{
for (timeTest t : timeCases) {
const auto actual = string(date_independent::clock::at(t.hour, t.minute));

BOOST_REQUIRE_MESSAGE(t.expected == actual, errorMsg(t.expected, actual, t.msg));
}
}

...

BOOST_AUTO_TEST_CASE(add_tests)
{
for (addTest a : addCases) {
const auto actual = string(date_independent::clock::at(a.hour, a.minute).plus(a.add));

BOOST_REQUIRE_MESSAGE(a.expected == actual, errorMsg(a.expected, actual, a.msg));
}
}

...

最佳答案

如果想在控制台输出你的类或将它写入文件,你必须覆盖 <<您类(class)的运营商。

std::ostream& operator<<(std::ostream& os, const person& person)
{
return os << person.first_name << " " << person.last_name;
}

如果你只想要一个 std::string , 只需添加一个 to_string返回类的字符串表示的方法。

class person
{
public:

std::string to_string() const
{
return first_name + " " + last_name;
}

private:

std::string first_name;
std::string last_name;
};

关于c++ - 就像在 python 中定义 __str__ 一样,在类上调用时如何覆盖 c++ 中的标准全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47938200/

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