c++ - 使用函数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.
解决方案
您需要分配对象 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;
}
推荐阅读
- javascript - 使用 chrome 存储在加载时执行功能
- c# - 如何使用 C# 驱动程序在 MongoDB 中获取集群时间
- javascript - Vue 组件显示两次是因为
- python-3.x - 如何使用 Selenium Python 单击锁定图像文件
- android - 如何在android java webview中检测USB摄像头
- http - IP是如何拆分的?
- php - Woocommerce 自动添加到特定产品的购物车功能
- c# - 强制参数化
- typescript - TypeScript 错误地定义了类型
- angular - 如何使用 Jasmine 在 Angular 中测试我的服务?