C++:基类中的字符串参数在派生类解构时进行解构
C++: String parameter in base class deconstructs when the derived class deconstruction
我有一个名为a的基类,其中包含一个字符串类型参数。
B类来源于A.
我定义类C具有参数A*A,并且将其分配给B.
在主函数中,我无法获得基类的字符串值,因为当b解构时,它变成了空白。
我希望它输出:
"Hello!"
"Hello!"
end
但输出是:
"Hello!"
end
这是我的代码:
class A {
public:
string str;
};
class B : public A {
public:
B(string _str) {
str = _str;
}
};
class C {
public:
A *a;
public:
void printOut() {
B b("Hello!");
a = &b;
cout << a->str << endl;
}
};
int main() {
C c;
c.printOut();
cout << c.a->str << endl;
cout << "end" << endl;
return 0;
}
我该怎么处理?
正确,因为B b("Hello!");
超出了作用域,c.a
现在是一个悬空指针,在被取消引用时会导致未定义的行为。如果你想让它超过作用域,你可以在堆上分配它:
class A {
public:
string str;
};
class B : public A {
public:
B(string _str) {
str = _str;
}
};
class C {
public:
A *a;
public:
void printOut() {
B* b = new B("Hello!");
a = b;
cout << a->str << endl;
}
};
int main() {
C c;
c.printOut();
cout << c.a->str << endl;
cout << "end" << endl;
delete c.a;
return 0;
}
不过,这很快就会变得一团糟,因为你必须跟踪自己分配的内存,并适当地调用delete
,考虑重新设计或使用智能指针。
为什么要存储A*
?你知道那不管用,所以别再这么做了。
制作一个A
对象的副本,或者它包含的字符串的副本,然后停止尝试做一些愚蠢的事情。
class A {
public:
string str;
};
class B : public A {
public:
B(string _str) {
str = _str;
}
};
class C {
public:
string str;
public:
void printOut() {
B b("Hello!");
str = b.str;
cout << str << endl;
}
};
int main() {
C c;
c.printOut();
cout << c.str << endl;
cout << "end" << endl;
return 0;
}
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"