C++ 错误 - 'char' 和 'int' 之前的预期主表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13494304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:24:05  来源:igfitidea点击:

C++ error - expected primary expression before 'char' and 'int'

c++inheritanceconstructor

提问by Naxical

#include<iostream>
#include<cstring>
using namespace std;
class Employee
{
    char name[5];
    int id;
    int age;
    public:
    Employee(char* a, int b, int c)
    {
        strcpy(name, a);
        id=b;
        age=c;
    }
};
class Officer: public Employee
{
    char officer_cadre[3];
    public:
    Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)
    {
        strcpy(officer_cadre, d);
    }
};
int main()
{
   Officer o1("Nakul", 1, 2, "ABC");
   return 0;
}

The above code is simple, but I'm not able to figure out why the compiler is throwing errors like 'expected primary expression before char' and 'expected primary expression before int'.

上面的代码很简单,但我无法弄清楚为什么编译器会抛出诸如“char 之前的预期主表达式”和“int 之前的预期主表达式”之类的错误。

回答by RonaldBarzell

Change this line:

更改此行:

Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)

To this:

对此:

Officer(char* a, int b, int c, char* d):Employee(a,b,c)

Also I am concerned about your declaration of officer_cadre. It's an array of character pointers, but there's no memory allocation. Was that the declaration you meant?

我也很担心你对offer_cadre 的声明。它是一个字符指针数组,但没有内存分配。那是你说的宣言吗?

回答by Doug T.

On this line

在这条线上

  Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)

You should just pass a,b, and c. Instead you are using the syntax to declare a,b, and c. When just referring to them you don't need the types. IE you should do:

你应该只通过 a、b 和 c。相反,您使用语法来声明 a、b 和 c。当只是引用它们时,您不需要类型。IE 你应该这样做:

  Officer(char* a, int b, int c, char* d):Employee(a, b, c)

You may have just accidentally copy-pasted the declaration into the child class's constructor.

您可能只是不小心将声明复制粘贴到子类的构造函数中。

回答by kord

Change

改变

char* officer_cadre[3];

to

char officer_cadre[3];