问题
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