0 c++ string inheritance derived-class
我有一个名为A的基类,包含一个字符串类型参数.
B类派生自A.
我定义类C有参数A*a,并将其分配给B.
在main函数中,我无法获取基类的字符串值,因为它在b解构时变为空白.
我希望它输出:
"Hello!"
"Hello!"
end
Run Code Online (Sandbox Code Playgroud)
但输出是:
"Hello!"
end
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
我怎么处理它?
正确,因为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;
}
Run Code Online (Sandbox Code Playgroud)
虽然因为你必须跟踪自己分配的内存并delete
适当调用,考虑重新设计或使用智能指针,这会变得非常快速.
归档时间: |
|
查看次数: |
97 次 |
最近记录: |