我有两个结构相似的类。
class A{
int a;
char *b;
float c;
A(char *str) { //allocate mem and assign to b }
};
class B{
int a;
char *b;
float c;
B(char *str) { //allocate mem and assign to b }
B(B & bref) { //properly copies all the data }
};
我想将B
的对象复制到A
的对象。以下转换是否正常?
A aobj("aobjstr");
B bobj("bobjstr");
bobj = aobj; //case 1
bobj = B(aobj); //case 2
案例 2 可行吗?当调用 B 的复制构造函数时,aobj
是否会被正确转换并解释为 B &
?
编辑:怎么样?
B bobj(aobj)
最佳答案
不,您不能在不编写转换构造函数或转换运算符的情况下在不相关的类型之间进行隐式转换。大概是你的编译器告诉你的;我的错误如下:
error: no match for ‘operator=’ in ‘bobj = aobj’
note: no known conversion for argument 1 from ‘A’ to ‘const B&’
error: no matching function for call to ‘B::B(A&)’
您可以通过给 B
一个转换构造函数来允许转换:
class B {
// ...
B(A const & a) { /* properly copy the data */ }
};
如果您不能更改类,那么您将需要一个非成员函数来进行转换;但这可能只有在类(class)成员公开时才有可能。在您的示例中,所有成员(包括构造函数)都是私有(private)的,因此根本无法使用这些类。据推测,您的真实代码并非如此。
如果你想过着危险的生活,你可以明确地将 A
对象重新解释为 B
,因为它们都是标准布局类型相同的数据成员:
// DANGER: this will break if the layout of either class changes
bobj = reinterpret_cast<B const &>(a);
请注意,由于您的类分配了内存,因此它可能需要在其析构函数中释放内存;为了避免双重删除,您还必须根据 Rule of Three 正确地实现复制构造函数和复制赋值运算符。 .
如果这一切听起来工作量太大,为什么不使用 std::string
,它会为您管理内存?
关于c++ - 在 C++ 中复制相似的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996520/