【问题标题】:C++ Passing pointers through class functions from main()C++ 通过 main() 中的类函数传递指针
【发布时间】:2013-10-14 03:47:37
【问题描述】:

我知道指针是经常被讨论的东西。我做了很多研究来尝试解决这个问题,但是一切都把我带到了死胡同。

我有一个作业要求我创建一个记录单个测试分数的课程。如果已经记录了测试分数并且新分数更高,则覆盖它。如果它已被记录并且新的分数较低,则什么也不做。如果没有记录,就记录下来。

这是我目前所拥有的:

//  CIS 235 exercise 7

#include <iostream>


using namespace::std;

//   declare a class for recording a test score
//   the data will be pointer to an integer, rather than an integer
//
//   - this exercise is designed to show how to work with pointer memory
//   - of course, we would NOT normally use a pointer for just an integer
//   - to illustrate the concepts, but keep the implementation simple,
//             integer data was used.  The general case would be object data,
//             not integer data

class testScore
{
   public:
   //  declare a default constructor - the pointer should be set to NULL
   testScore();
   //  declare a function that returns a bool, indicating if the test has been taken
   bool hasTestTaken();
   //  declare a function to record the test score, the parameter will be an integer
   //  use the following rules
   //  -  if no test has been taken, allocate memory and record the score
   //  -  if a test has been taken and the parameter is less than or equal to
   //         the score, do nothing
   //  -  if the test has been taken and the parameter is  higher than the score,
   //         - release the old memory
   //         - allocate new memory
   //         - record the score
   void recordScore(int *myScore);
   //   declare a function to print the score to an ostream parameter
   //   if the test has not been taken, send an appropriate message to the ostream
   //         otherwise print the score
   void printScore(ostream &out);
   //   declare the destructor
   //   be CAREFUL, you will need an if statement in your destructor
   ~testScore();

   private:
   //  declare the data needed to implement the class
   bool testTaken;
   int *score;
 };

//  write the 5 member functions

testScore::testScore() : score(NULL)
{
//  declare a default constructor - the pointer should be set to NULL
}

bool testScore::hasTestTaken()
{
   //  declare a function that returns a bool, indicating if the test has been taken
   return testTaken;
}

void testScore::recordScore(int *myScore)
{
   if(testTaken == false)
   {
                testTaken = true;
                *score = *myScore;
   }
   else if(testTaken == true && *myScore > *score)
   {
                score = NULL;
                delete score;
                score = new int;
                *score = *myScore;
   }

}

void testScore::printScore(ostream& out)
{
      //   declare a function to print the score to an ostream parameter
   //   if the test has not been taken, send an appropriate message to the ostream
   //         otherwise print the score
     if(testTaken)
     {
                  out << *score << endl;
     }
     else
         out << "The test has not been taken!" << endl;
}

testScore::~testScore()
{
   //   declare the destructor
   //   be CAREFUL, you will need an if statement in your destructor
   if(score != NULL)
   {
             score = NULL;
             delete score;
   }
   else
       delete score;

}

//  test the class member functions
//    - declare an object, but do NOT record a score for the object

//    - declare a second object and record the scores of 83, 78, 92
//       use appropriate member print functions to verify your code
//int abc = 83;
int abc = 0;
int main()
{
//    int abc = 0;
//    int * score2;
//    myTestScore = new int;
//    *myTestScore = 83;

    testScore firstScore;
    firstScore.printScore(cout);

    testScore secondScore;
//    secondScore.recordScore(&abc);
      secondScore.recordScore(&abc);
//    secondScore.printScore(cout);
//    *myTestScore = 78;
//    secondScore.recordScore(myTestScore);
//    secondScore.printScore(cout);
//    *myTestScore = 92;
//    secondScore.recordScore(myTestScore);
//    secondScore.printScore(cout);


   system("PAUSE");
   return 0;
}

指针对我来说是相当新的东西...我查过它们,查过,查过,但我似乎总是把它们弄错。

知道了这一点,我知道我的 recordScore 函数可能做错了什么,但我不知道是什么。

我现在的主要问题是 firstScore 运行良好(耶!我做对了……也许)但是 secondScore 不会记录分数。我尝试了几种不同的方法。

  1. 我把 int abc = 0;上面的 int main()

    • 调用 recordScore 时编译并运行良好
    • 当我调用 printScore 时编译并崩溃
      • 输出显示:该测试已完成!按任意键继续...(崩溃)
  2. 我把 int abc = 0;在 int main() 内部,但在其他任何事情之前

    • 在将任何内容输出到控制台之前调用 recordScore 时崩溃

如果我的 int main() 看起来像这样,这也会崩溃:

int main()
{
    int abc = 0;

    testScore firstScore;
    firstScore.printScore(cout);


   system("PAUSE");
   return 0;
}

我不知道为什么T.T

我也试过了:

声明

int *myTestScore;
myTestScore = new int;
*myTestScore = 83;

在 main() 内部,但在其他任何事情之前,并通过以下方式将 myTestScore 传递给 recordScore:

&myTestScore

编译错误:没有匹配函数调用'testScore::recordScore(int**); 在 secondScore.recordScore 行。

*myTestScore

编译错误:从 'int' 到 'int*' 的无效转换 在 secondScore.recordScore 行。

myTestScore

没有编译错误,在输出到控制台之前运行时崩溃

我尝试过声明:

int *myTestScore = 83; 

在 int main() 内部 编译错误:从 'int' 到 'int*' 的无效转换 在 int *myTestScore = 83 行上。

我还尝试了各种方法将 recordScore 更改为使用 &'s 和 *'s 而两者都不使用以及两者的不同组合。

我现在没有什么可以尝试的想法,即使在研究之后我也想不出任何东西。我试图问我的教授(现在已经有一个星期了,它是在线课程),打电话给她,给她发电子邮件,但她没有回答我的任何问题,甚至没有回答我的会议请求。

我觉得这里有些简单的东西我没有掌握,我非常感谢任何人可以帮助我解决这个问题。

非常感谢您的宝贵时间。


变化:

testScore::testScore() : score(NULL), testTaken(false) // didnt change because instructor instructions, but did move testTaken up cause that is where it should be
{
    //  declare a default constructor - the pointer should be set to NULL
}

void testScore::recordScore(int myScore)
{
   if(testTaken == false)
   {
                testTaken = true;
                score = &myScore;
                cout << *score << endl; //this prints correctly, 0
   }
   else if(testTaken == true && myScore > *score)
   {
                //removed the score = NULL to avoid a memory leak (I think this is correct now?)
                delete score;
                score = new int;
                score = &myScore;
   }

}

void testScore::printScore(ostream& out)//no changes, just easier to access to you dont have to keep scrolling up
{
      //   declare a function to print the score to an ostream parameter
   //   if the test has not been taken, send an appropriate message to the ostream
   //         otherwise print the score
     if(testTaken)
     {
                  out << *score << endl; //outputs incorrect 4469696
     }
     else
         out << "The test has not been taken!" << endl;
}

int main()
{
    int abc = 0;

    testScore firstScore;
    firstScore.printScore(cout);

    testScore secondScore;
    secondScore.recordScore(abc);
    secondScore.printScore(cout);

   system("PAUSE");
   return 0;
}

输出: 没有参加这个测试! 0 4469696 按任意键继续...


最终的工作产品:

//  CIS 235 exercise 7

#include <iostream>


using namespace::std;

//   declare a class for recording a test score
//   the data will be pointer to an integer, rather than an integer
//
//   - this exercise is designed to show how to work with pointer memory
//   - of course, we would NOT normally use a pointer for just an integer
//   - to illustrate the concepts, but keep the implementation simple,
//             integer data was used.  The general case would be object data,
//             not integer data

class testScore
{
   public:
   //  declare a default constructor - the pointer should be set to NULL
   testScore();
   //  declare a function that returns a bool, indicating if the test has been taken
   bool hasTestTaken();
   //  declare a function to record the test score, the parameter will be an integer
   //  use the following rules
   //  -  if no test has been taken, allocate memory and record the score
   //  -  if a test has been taken and the parameter is less than or equal to
   //         the score, do nothing
   //  -  if the test has been taken and the parameter is  higher than the score,
   //         - release the old memory
   //         - allocate new memory
   //         - record the score
   void recordScore(int * myScore);
   //   declare a function to print the score to an ostream parameter
   //   if the test has not been taken, send an appropriate message to the ostream
   //         otherwise print the score
   void printScore(ostream &out);
   //   declare the destructor
   //   be CAREFUL, you will need an if statement in your destructor
   ~testScore();

   private:
   //  declare the data needed to implement the class
   bool testTaken;
   int *score;
 };

//  write the 5 member functions

testScore::testScore() : score(NULL), testTaken(false)
{
    //  declare a default constructor - the pointer should be set to NULL
}

bool testScore::hasTestTaken()
{
   //  declare a function that returns a bool, indicating if the test has been taken
   return testTaken;
}

void testScore::recordScore(int * myScore)
{
   if(testTaken == false)
   {
                score = new int;
                testTaken = true;
                *score = *myScore;
   }
   else if(testTaken == true && *myScore > *score)
   {
                delete score;
                score = new int;
                *score = *myScore;
   }

}

void testScore::printScore(ostream& out)
{
      //   declare a function to print the score to an ostream parameter
   //   if the test has not been taken, send an appropriate message to the ostream
   //         otherwise print the score
     if(testTaken)
     {
                  out << *score << endl;
     }
     else
         out << "The test has not been taken!" << endl;
}

testScore::~testScore()
{
   //   declare the destructor
   //   be CAREFUL, you will need an if statement in your destructor
   if(score != NULL)
   {
             delete score;
   }

}

//  test the class member functions
//    - declare an object, but do NOT record a score for the object

//    - declare a second object and record the scores of 83, 78, 92
//       use appropriate member print functions to verify your code
int main()
{
    int abc = 83;

    testScore firstScore;
    firstScore.printScore(cout);

    testScore secondScore;
    secondScore.recordScore(&abc);
    secondScore.printScore(cout);

    abc = 78;
    secondScore.recordScore(&abc);
    secondScore.printScore(cout);

    abc = 92;
    secondScore.recordScore(&abc);
    secondScore.printScore(cout);

   system("PAUSE");
   return 0;
}

非常感谢,我实际上从中学到了很多东西,还学到了一些新术语:)

【问题讨论】:

  • 声明一个记录考试成绩的函数,参数为整数。您声明它采用指向整数的指针。阅读您的问题,我建议您停下来,深吸一口气,然后重新阅读有关指针的材料。如果你写了int* myScore = 83;,需要问怎么回事,说明你需要多学习。
  • Merr,一开始她说过://声明一个记录考试成绩的类//数据将是一个整数的指针,而不是一个整数
  • 这是类的要求,不是recordSCore的签名。
  • 好吧...所以,如果我给它发送一个int,并切换一些东西,我可以让它正确记录分数,但打印功能会中断...上传新代码?

标签: c++ class pointers


【解决方案1】:

主要问题是在默认构造函数中你将NULL赋值给了score,所以指针会指向无效的内存。所以,当你调用recordStore时,当程序来到这个指令时:

 *score = *myScore;

这会导致分段错误,当您尝试覆盖程序未使用的内存部分时会发生错误。

程序不会在 printScore 中崩溃,因为读取无效指针不是错误,但它会读取垃圾数据。

编辑:根据您的分配,如果尚未进行测试,则必须在recordStore中分配指针,因此在recordStore中更改此部分:

if(testTaken == false)
{
                testTaken = true;
                *score = *myScore;
}

到这里:

if(testTaken == false)
{
                score = new int;
                testTaken = true;
                *score = *myScore;
}

当你做delete部分时,你首先将指针分配给NULL,然后删除它;所以程序会尝试删除NULL指针(这不会导致错误),用于score的内存没有被释放,导致内存泄漏

【讨论】:

  • 啊,我没有意识到删除的事情。谢谢!至于分数……我的教练希望它设置为 NULL,所以我必须:( - 但是你提供的关于指针对 null 无效的信息很有用,也谢谢你!但是,在 recordScore 下,当它 cout 在那里时,它会正确打印...当它到达 printScore 时,它​​会在此过程中以某种方式更改回 NULL,或者可能只是垃圾,或者其他东西,我不完全确定。更新代码跨度>
  • 如果您在谈论更改部分,当您通过值而不是指针传递 int 时,将传递 abc 的副本。并且该副本将在功能结束后被删除。所以后面会是垃圾值。
猜你喜欢
  • 1970-01-01
  • 2011-07-12
  • 2021-02-24
  • 2021-06-24
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多