当函数返回值时,如何为指针赋值? [英] How do I assign a value to a pointer when the value is being returned by a function?

查看:171
本文介绍了当函数返回值时,如何为指针赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// inheritance , polymorphism
#include<iostream>
#include<string>

using namespace std;

class person
{
	public :
		int age;
		string name;
		string get_name()
		{
			cout<<"Please enter the name"<<endl;
			cin>>name;
			return name;
		}
		int get_age()
		{
			cout<<"enter the age"<<endl;
			cin>>age;
			return age;
		}
};

class student : public person
{
  private : 
  int id;
  char section;
  public:
  int get_id(){
  	cout<<"enter the id of the student"<<endl;
  	cin>>id;
  	return id;
  }
  char get_section()
  {
  	cout<<"enter the section"<<endl;
  	cin>>section;
  	return section;
}	
};

int main()
{
int *a;
string n;
student s;
int i;
char sec;
char c;
n=s.get_name();
*a=s.get_age();
cout<<"is this person a student? please enter y or n"<<endl;
cin>>c;
if (c=='y')
{
	i=s.get_id();
	sec=s.get_section();
	cout<<" My name is "<<n<<" my age is "<<*a<<" my id is "<<i<<" my sec is "<<sec;
}
if (c=='n')
{

	cout<<"My name is "<<n<<" my age is "<<*a<<" I am not a student ";
}

}





我尝试过:



age在main函数中声明为* a。如何为它赋予get_age()返回的值。



What I have tried:

age is declared as *a in main function. how to assign it the value that get_age() is returning.

推荐答案

您的代码部分正确但缺少重要步骤。在班级学生中,值 age 永远不会被设置。

构造函数中有两种方法:

构造函数和成员初始化列表 - cppreference.com [ ^ ]



或获取和设置方法:

在C ++中获取和设置方法的目的 [ ^ ]



第二种方法应该完全适合你。只需将set方法添加到您的类中。
Your code is partly correct but missing important steps. In the class student the value age never gets set.
Two ways of doing this are in the constructor:
Constructors and member initializer lists - cppreference.com[^]

or by get and set methods:
The purpose of get and set methods in C++[^]

The second approach should suit you perfectly. Just add set methods to your class.


当您不理解代码正在执行的操作或为什么执行此操作时,答案是调试程序

使用调试器查看代码正在执行的操作。它允许你逐行执行第1行并在执行时检查变量,它是一个令人难以置信的学习工具。



调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做的比较。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于当函数返回值时,如何为指针赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆