如何使指针显示对象的字符串变量?

问题描述 投票:0回答:1

我做了一个简单的测试程序,因为我无法弄清楚为什么在另一个作用域内创建对象时指针无法访问对象的整数值,而指针却无法显示字符串变量。当我删除这些括号时,指针通常会返回字符串的变量,而带有括号的字符串中几乎没有任何内容。

#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;
}
c++ string pointers scope undefined-behavior
1个回答
0
投票

ab对象的生存时间在控件退出定义对象的复合语句后停止。因此,超出范围的指针l1l2具有无效值。

TEST* l1;
TEST* l2;

{
    TEST a{ 1,2, "asd" }, b{ rand() % 20 + 10,1, "asdf" };
    l1 = &a;
    l2 = &b;
}

*l1 + *l2;

对于数据成员string a;,称为其析构函数。结果,程序具有未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.