gpt4 book ai didi

C++ 两个类相互转换并调用它们的函数

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:44 24 4
gpt4 key购买 nike

我有两个类。其中一个没有返回值和抛出值,另一个有返回类型但不抛出任何东西。我想要实现的是在彼此之间转换类并调用它们的函数,我可以调用函数时不使用静态方法。代码块示例;

  class ThrowableA{
public:
void getvalue();
}

class ReturnTypeA{
public:
int getvalue();
}


class BaseTypeA{//this will accept ThrowableA and ReturnTypeA
...
};

BaseTypeA * d = new ThrowableA();
d->getvalue(); // this will call ThrowableA::getvalue
(do something with d)->getvalue();//this will call ReturnTypeA::getvalue
BaseTypeA * f = new ReturnTypeA();
f->getvalue();//this will call ReturnTypeA::getvalue
(do something with f)->getvalue();//this will call ThrowableA::getvalue

最佳答案

我认为您需要定义复制构造函数(或移动构造函数);或者,您可以定义转换运算符:

class ThrowableA : public BaseTypeA
{
public:
explicit ThrowableA(const ReturnTypeA& rt);
void getvalue();
// or explicit operator ReturnTypeA() const;
}

class ReturnTypeA : public BaseTypeA
{
public:
explicit ReturnTypeA(const ThrowableA& ta);
int getvalue();
// or explicit operator ThrowableA() const;
}

explicit 关键字表示只有在您的代码明确要求时才会发生转换。如果没有该关键字,该语言将在必要时自动执行最多一次转换,这可能会导致意外。 Bjarne Stroustrup's FAQ提到显式转换运算符;它显然是 C++11 的特性(而显式构造函数来自 C++03)。

来回转换不需要继承,但似乎与您想要的设置相匹配。

然后,要从一种转换为另一种,只需创建另一种类型的另一个对象:

ThrowableA ta;
// Work with ta, add data, etc.
ReturnTypeA ra(ta);
// Use ra.

关于C++ 两个类相互转换并调用它们的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846362/

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