【发布时间】:2016-05-16 19:31:05
【问题描述】:
我不是编码新手,但我是 Visual Studios。对于我的一生,我无法弄清楚为什么会出现以下语法错误。代码拒绝让我声明对象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 begin\n");
for (int i = 0; i < 200; i++) {
m = Match();
printf("%s ... %s\n", 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
【问题讨论】:
-
它只能是C 或 C++,所以我要去掉C标签。
-
使用
#pragma once或宏包含守卫,不能同时使用。 -
Match m = new Match();-->Match* mPtr = new Match();。或者干脆Match m; -
using namespace std;在标题中可以在很多方面毁掉你的一天。在这里阅读更多:stackoverflow.com/questions/1452721/… -
m.printStr.c_str()应该是m.printStr().c_str()。除了缺少Match的定义之外,指针混淆解决了所有问题,我无法重现。
标签: c++ visual-studio visual-studio-2015