Expected unqualified-id before ')' token? [closed]

Deadly 提交于 2020-06-18 11:45:33

问题


I want to create a base class and get an error with my initializer list in default constructor. Here are the errors I'm getting:

giasuc.cpp:3:8: error: expected unqualified-id before ')' token
 GiaSuc(): ten(""), soConSinh(0), soLitSua(0) {
        ^
giasuc.cpp:6:14: error: expected ')' before '&' token
 GiaSuc(GiaSuc& mGiasuc): ten(mGiasuc.ten), soConSinh(mGiasuc.soConSinh), soLitS
ua(mGiasuc.soLitSua) {
              ^
giasuc.cpp:9:20: error: expected ')' before '&' token
 GiaSuc(std::string &mTen, short mSoCon = 0, short mLitSua = 0): ten(mTen), soCo
nSinh(mSoCon), soLitSua(mLitSua) {
                    ^

And this is the class I am building (giasuc.h):

#ifndef GIA_SUC_H
#define GIA_SUC_H

#include <iostream>
#include <string>

class GiaSuc {
protected:
    std::string ten;
    short soConSinh;
    short soLitSua;

public:
    GiaSuc();
    GiaSuc(GiaSuc& mGiasuc);
    GiaSuc(std::string &mTen, short mSoCon, short mLitSua);
    virtual void keu() = 0;
    virtual ~GiaSuc() = 0;
};

#endif // GIA_SUC_H

And giasuc.cpp:

#include "giasuc.h"
#include <string>
GiaSuc(): ten(""), soConSinh(0), soLitSua(0) {
}

GiaSuc(GiaSuc& mGiasuc): ten(mGiasuc.ten), soConSinh(mGiasuc.soConSinh), soLitSua(mGiasuc.soLitSua) {
}

GiaSuc(std::string &mTen, short mSoCon = 0, short mLitSua = 0): ten(mTen), soConSinh(mSoCon), soLitSua(mLitSua) {
}

I am using MinGW g++ (GCC) 4.9.3, and compiling it with:

g++ -Wall -Wpedantic -Weffc++ -ansi -c giasuc.cpp


回答1:


When you define member functions of a class outside the class definition, you need to use the scope operator :: and the class name to tell the compiler what class they belong to.

Like

GiaSuc::GiaSuc(): ten(""), soConSinh(0), soLitSua(0) { ... }



回答2:


In your .cpp file, the constructor should not be GiaSuc(). It should be GiaSuc::GiaSuc(). The constructor needs to be qualified by the class name.

#include "giasuc.h"
#include <string>
GiaSuc::GiaSuc(): ten(""), soConSinh(0), soLitSua(0) {
}

GiaSuc::GiaSuc(GiaSuc& mGiasuc): ten(mGiasuc.ten), soConSinh(mGiasuc.soConSinh), soLitSua(mGiasuc.soLitSua) {
}

GiaSuc::GiaSuc(std::string &mTen, short mSoCon = 0, short mLitSua = 0): ten(mTen), soConSinh(mSoCon), soLitSua(mLitSua) {
}



回答3:


You forgot the Scope resolution operator that's required while defining your functions outside of your class #include "GiaSuc.h"

GiaSuc::GiaSuc(): ten(""), soConSinh(0), soLitSua(0) {
}

 GiaSuc::GiaSuc(GiaSuc& mGiasuc): ten(mGiasuc.ten), soConSinh(mGiasuc.soConSinh),    soLitSua(mGiasuc.soLitSua) {
}

GiaSuc::GiaSuc(std::string &mTen, short mSoCon = 0, short mLitSua = 0): ten(mTen), soConSinh(mSoCon), soLitSua(mLitSua) {
}

http://en.cppreference.com/w/cpp/language/lookup



来源:https://stackoverflow.com/questions/37222415/expected-unqualified-id-before-token

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!