如何让指针显示对象的字符串变量?
How to make pointer show object's string variable?
我做了一个简单的测试程序,因为我无法弄清楚为什么当在另一个范围内创建对象时指针访问对象的整数值而它不能显示字符串变量。当我删除这些括号时,指针 returns 字符串的变量通常是带括号的,而这个字符串中什么也没有。
#include <iostream>
#include <stdlib.h>
using namespace std;
int test() {
cout << "NO ELO MORDECZKI" << endl;
return 1;
}
class TEST {
public:
int i;
int j;
string a;
TEST(int i, int j, string a) { this->i = i; this->j = j; this->a=a; }
void operator +(TEST b) {
this->i = this->i - b.i;
if (i < 0) {
cout << b.i << endl;
b.i -= - (test()*100);
cout << b.i << endl;
}
}
};
int main() {
TEST* l1;
TEST* l2;
{
TEST a{ 1,2, "asd" }, b{ rand() % 20 + 10,1, "asdf" };
l1 = &a;
l2 = &b;
}
*l1 + *l2;
cout << "->" << l1->i << "<-" << endl;
}
对象a
和b
的生命周期在控件退出定义对象的复合语句后停止。因此在范围之外,指针 l1
和 l2
具有无效值。
TEST* l1;
TEST* l2;
{
TEST a{ 1,2, "asd" }, b{ rand() % 20 + 10,1, "asdf" };
l1 = &a;
l2 = &b;
}
*l1 + *l2;
对于数据成员string a;
,调用了它的析构函数。因此,该程序具有未定义的行为。
我做了一个简单的测试程序,因为我无法弄清楚为什么当在另一个范围内创建对象时指针访问对象的整数值而它不能显示字符串变量。当我删除这些括号时,指针 returns 字符串的变量通常是带括号的,而这个字符串中什么也没有。
#include <iostream>
#include <stdlib.h>
using namespace std;
int test() {
cout << "NO ELO MORDECZKI" << endl;
return 1;
}
class TEST {
public:
int i;
int j;
string a;
TEST(int i, int j, string a) { this->i = i; this->j = j; this->a=a; }
void operator +(TEST b) {
this->i = this->i - b.i;
if (i < 0) {
cout << b.i << endl;
b.i -= - (test()*100);
cout << b.i << endl;
}
}
};
int main() {
TEST* l1;
TEST* l2;
{
TEST a{ 1,2, "asd" }, b{ rand() % 20 + 10,1, "asdf" };
l1 = &a;
l2 = &b;
}
*l1 + *l2;
cout << "->" << l1->i << "<-" << endl;
}
对象a
和b
的生命周期在控件退出定义对象的复合语句后停止。因此在范围之外,指针 l1
和 l2
具有无效值。
TEST* l1;
TEST* l2;
{
TEST a{ 1,2, "asd" }, b{ rand() % 20 + 10,1, "asdf" };
l1 = &a;
l2 = &b;
}
*l1 + *l2;
对于数据成员string a;
,调用了它的析构函数。因此,该程序具有未定义的行为。