c++ - 需要有关指针和耗时程序的建议。如何修复无效操作数和无法转换错误?

标签 c++ pointers struct

我正在尝试编写一个程序来区分用户输入的两次输入。我不知道该怎么做。我收到错误:

第 27 行|错误:“int”和“const MyTime*”类型的无效操作数转换为二进制“operator-”|

第 |39 行|错误:无法将参数“1”的“MyTime”转换为“const MyTime*”到“int DetermineElapsedTime(const MyTime*, const MyTime*)”|

我在这个问题上也需要很多帮助。我没有好的类(class),我的课本就像编程的悬崖笔记。这将是我在这所大学的最后一个类。我使用的 C++ teztbook(我自己的不是用于类的)是 Sam 的 C++ 每天一小时。

#include <iostream>
#include<cstdlib>
#include<cstring>

using namespace std;
struct MyTime { int hours, minutes, seconds; };
int DetermineElapsedTime(const MyTime *t1, const MyTime *t2);

long t1, t2;

int DetermineElapsedTime(const MyTime *t1, const MyTime *t2)
{
    return((int)t2-t1);
}


int main(void)
{
    char delim1, delim2;
    MyTime tm, tm2;
    cout << "Input two formats for the time. Separate each with a space. Ex: hr:min:sec\n";
    cin >> tm.hours >> delim1 >> tm.minutes >> delim2 >> tm.seconds;
    cin >> tm2.hours >> delim1 >> tm2.minutes >> delim2 >> tm2.seconds;

    DetermineElapsedTime(tm, tm2);

    return 0;

}

我必须先修正错误。有人有什么想法吗??

最佳答案

请查看您对 DetermineElapsedTime 的实现。

struct MyTime { int hours, minutes, seconds; };

...

int DetermineElapsedTime(const MyTime *t1, const MyTime *t2)
{
    return((int)t2-t1);
}

编译器应该如何知道你对这行的意思

    return((int)t2-t1);

您不能简单地减去这两个结构。您必须自己实现。

编辑:

更好地使用

int DetermineElapsedTime(MyTime &t1, MyTime &t2)

这更像 C++。

我最终得到了(仍然很丑,但目前只剩下主要问题)

您仍然需要找到一个解决方案来减去您的 MyTime 结构中的数据。

#include <iostream>
#include<cstdlib>
#include<cstring>

using namespace std;
struct MyTime { int hours, minutes, seconds; };


int DetermineElapsedTime(MyTime &t1, MyTime &t2)
{
    // TODO: This is not correct! Implement the correct way.
    return((int)t2-t1);
}

int main(void)
{
    char delim1, delim2;
    MyTime tm, tm2;
    cout << "Input two formats for the time. Separate each with a space. Ex: hr:min:sec\n";
    cin >> tm.hours >> delim1 >> tm.minutes >> delim2 >> tm.seconds;
    cin >> tm2.hours >> delim1 >> tm2.minutes >> delim2 >> tm2.seconds;

    DetermineElapsedTime(tm, tm2);

    return 0;

}

关于c++ - 需要有关指针和耗时程序的建议。如何修复无效操作数和无法转换错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13338582/

相关文章:

c++ - 如何使用 C++ 模板推断编译时 const char 字符串的大小?

c++ - 寻找最近的邻居 - OpenCV

c++ - 有没有更简单的方法让键盘输入返回字符(SFML)?

c - 小端和大端中 int 的地址是否相同?

c++ - 对字符数组中的单词进行排序

c++ - 将 Z3 模型值导入 C++

c - 将 char 数组从指针复制到行文件后的奇怪输出

C++:从(不是)类实例获取类型

c - 指向 C 中 struct 的函数返回矩阵的指针

c - 在c中的结构中初始化灵活的结构指针数组