【问题标题】:How to make pointer show object's string variable?如何使指针显示对象的字符串变量?
【发布时间】:2020-05-10 11:36:14
【问题描述】:

我制作了一个简单的测试程序,因为我无法弄清楚为什么指针访问对象的整数值,而当在另一个范围内创建对象时它无法显示字符串变量。当我删除这些括号时,指针通常会返回字符串的变量,而使用括号时,这个字符串内什么都没有。

#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】:

    对象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;,调用了它的析构函数。因此,程序具有未定义的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2014-08-02
      • 2019-11-19
      相关资源
      最近更新 更多