C++谁将结构存储在堆栈中(STL)

tsi*_*sid -2 c++ stack struct stl

我遇到这样的问题: C++:将结构存储在堆栈中

我的代码:

#include <stdio.h>
#include <stack>
#include <iostream>
#include <string>
using namespace std;

struct adresse{

    string info;
};

int main(){

    string eingabe;
    stack<adresse> Stack1;

    cout << "Bitte Ausdruck eingeben: " << endl;
    getline( cin, eingabe);

    adresse* temp;
    temp = new adresse;
    temp->info = eingabe[0];
    Stack1.push(temp);

    return 0;  
}
Run Code Online (Sandbox Code Playgroud)

错误是:

reference to type 'const value_type'(aka 'const adresse') could not bind to an 
lvalue of type 'adresse *'Stack1.push(temp);
Run Code Online (Sandbox Code Playgroud)

怎么了?

谢谢

汤米

Yak*_*ont 5

adresse temp;
temp.info = eingabe;
Stack1.push(temp); // maybe `std::move(temp)` instead of `temp`
Run Code Online (Sandbox Code Playgroud)

而不是new和你做的东西temp. new这里不需要. [0]不需要.指针不是必需的.

一般来说,new意味着"创建一个副本,我将手动管理其生命周期,并且访问速度较慢".它返回指向您new编辑的内容的指针.如果您不需要对创建的生命周期进行细粒度控制,请在堆栈上创建它.

在一些现代C++编码样式中,new不鼓励对特定低级资源管理功能之外的所有调用(诸如make_sharedmake_uniqueboost::variant类似之类).但是你仍然需要理解指针.

您创建了一个指向某些数据的指针,并尝试将其存储在需要某些数据值的容器中.容器需要引用它将复制的现有数据块:您为它指定了一些指向某些数据的指针.这些类型不同,因此编译器给出了一个错误,指出无法自动从一种类型转换为另一种类型.