首页 > 解决方案 > 使用函数c ++打印结构指针

问题描述

问题是程序在使用指针的时候没有打印任何值,我搜了很多,似乎没有解决办法。有任何想法吗?

#include <iostream>
using namespace std;

struct Brok{
    string name;
    int age;

    void pt(){
        cout << "Name : " << name << "\nAge : " << age;
    }
};


int main()
{
    Brok *a1;
    a1->name = "John Wick";
    a1->age = 46;
    a1->pt();

    return 0;
}

输出:



...Program finished with exit code 0
Press ENTER to exit console.

标签: c++pointersstruct

解决方案


您需要分配对象 a1 是“指向”,例如Brok *a1 = new Brok();.

例子:

/*
 * SAMPLE OUTPUT:
 *   g++ -Wall -pedantic -o x1 x1.cpp
 *   ./x1
 *   Name : John Wick
 *   Age : 46
 */
#include <iostream>
using namespace std;

struct Brok{
    string name;
    int age;

    void pt(){
        cout << "Name : " << name << "\nAge : " << age;
    }
};


int main()
{
    Brok *a1 = new Brok();
    a1->name = "John Wick";
    a1->age = 46;
    a1->pt();

    return 0;
}

推荐阅读