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

问题描述 投票:1回答:1

主要问题:

在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的类,并使该类具有一个名为at的公共函数,它将接受两个参数(在本例中为2个整数小时和分钟)”。我使函数成为static函数,因为测试代码并没有真正实例化时钟对象。我还将返回值设为std::string类型。它适用于前几个测试用例。不幸的是,我接着遇到了这个测试代码:

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

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

所以我的问题再一次是,我的假设是这个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));
    }
}

...
c++ string
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.