【问题标题】:Error instantiating custom class time when iostream is included包含 iostream 时实例化自定义类时间时出错
【发布时间】:2018-02-11 09:56:57
【问题描述】:

代码如下:

//main.cpp
#include <iostream>
#include "time.h"

int main(int argc, char** argv) {
    time::time t;
    return 0;
}

//time.cpp
#include "time.h"
#include <iostream>
#include <iomanip>
#include <stdexcept>
using namespace std;

time::time(){
    ore = minuti = secondi = 0;
} //costruttore senza argomenti

void time::setTime(int h,int m, int s){
    if(!(h<=0 && h>24)&& !(m<0 && m>60)&&!(s<=0 && s>60)){
        ore = h;
        minuti = m;
        secondi = s;
    }else{throw invalid_argument("ore,minuti e secondi non validi!!");}
}//fine del settaggio del tempo

void time::printUniversal(){
    cout << ore << ":" << minuti << ":" << secondi;
} //fine della stampa

void time::printStandard(){
    cout << ((ore == 0 || ore == 12) ? 12 : ore % 12) <<  ":" << setfill('0') << minuti << ":" << secondi << (ore < 12 ? " AM: ": " PM");
} // fine della stampa standard

//time.h
#ifndef TIME_H
#define TIME_H

class time{
public:
    time();
    void setTime(int,int,int);
    void printUniversal();
    void printStandard();
private:
    int ore;
    int minuti;
    int secondi;
};

#endif /* TIME_H */

编译器错误:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:4:10: error: expected ‘;’ before ‘t’
     time t;

【问题讨论】:

  • 这是我创建的类。
  • time 在全局命名空间中。
  • 在 main 中,不要使用time::time t;,而是使用time t;time 类位于全局命名空间中。如果您真的想要time::time,则需要将所有class time 仍然放在namespace time { ... } 内。这种同名可能会让人感到困惑。

标签: c++ oop


【解决方案1】:

作为commenters have alluded to,您的类time 位于全局namespace 中(即它不在自己或另一个namespace 中),因此引用它的正确方法是:

int main()
{
    time t;
}

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2016-09-28
    • 2015-01-02
    • 2015-04-30
    • 2016-06-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多