C++对象未声明的标识符



我不是代码新手,但我是Visual Studio的新手。就我的一生而言,我不明白为什么我会出现以下语法错误。代码拒绝允许我声明对象Match m = new Match();

Main.cpp

#include <iostream>
#include <string>
#include <time.h>
#include "Match.h"
#include "stdafx.h"
using namespace std;
const int NUM_TRIALS = 100000;
int main()
{
    Match m = new Match();
    printf("Program beginn");
    for (int i = 0; i < 200; i++) {
        m = Match();
        printf("%s ... %sn", m.to_str123().c_str(), m.printStr.c_str());
    }
    printf("Program end.n");
    return 0;
}

Match.h

#pragma once
#ifndef MATCH_H_
#define MATCH_H_
#include <string>
#include <iostream>
#include <time.h>
using namespace std;
#define HERO_PER_TEAM 3
#define NUM_HERO 10
class Match {
public:
    Match();
    ~Match();
    string to_str123();
    string printStr();
private:
    char teams[HERO_PER_TEAM * 2];
};
#endif

错误消息

Error   C2065   'Match': undeclared identifier  ConsoleApplication1 
Error   C2146   syntax error: missing ';' before identifier 'm' ConsoleApplication1 
Error   C2065   'm': undeclared identifier  ConsoleApplication1 
Error   C2061   syntax error: identifier 'Match'    ConsoleApplication1
Error   C2065   'm': undeclared identifier  ConsoleApplication1 
Error   C3861   'Match': identifier not found   ConsoleApplication1 
Error   C2065   'm': undeclared identifier  ConsoleApplication1 
Error   C2228   left of '.to_str123' must have class/struct/union   ConsoleApplication1 
Error   C2228   left of '.c_str' must have class/struct/union   ConsoleApplication1 
Error   C2228   left of '.printStr' must have class/struct/union    ConsoleApplication1

您正在使用new为非指针类型赋值。如果你想要一个指针,你可以使用:

Match* m = new Match();

否则,就这样声明:

Match m;

由于m没有被识别为对象,您也会得到所有其他错误。

此外,您应该能够使用#pragma once来代替标准的include防护。

new运算符使用给定的构造函数返回一个指向初始化对象的指针。您在这里所做的是java语法。要正确地执行此操作,您必须创建一个指向该类型对象的指针:Match *m = new Match();。然后,不要使用m.printStr,而是使用m->printStr,并且一定不要忘记删除使用delete m分配的内存。或者您可以简单地使用Match m();Match m = Match()在堆栈上分配它。然后您仍然可以使用表单m.printStr,并且不需要担心删除内存。

最新更新