Error extra qualification on member

В чем причина ошибки extra qualification C++ Решение и ответ на вопрос 1601508

denbi00

0 / 0 / 0

Регистрация: 21.11.2014

Сообщений: 11

1

04.12.2015, 03:00. Показов 22609. Ответов 16

Метки нет (Все метки)


Видает ошибку [Error] extra qualification ‘RyadokIdentifier::’ on member ‘Lowercase’ [-fpermissive] в чем причина

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <iostream>
#include <string>
#include <windows.h>
 
using namespace std;
 
class Ryadok{
 
protected:
    int len;
    char *strng;
public:
    Ryadok()// конструктор без параметрів
    {
        strng = NULL;
        len = 0;
    }
    Ryadok(char *sUser) //Конструктор що приймає як параметр Сі-рядок;
    {
        len = strlen(sUser);
        strng = new char[len + 1];
        // Ініціалізація стрічкою, переданої користувачем
        strcpy(strng, sUser);
 
    }
    Ryadok(const Ryadok &sUser) //Конструктор копіювання;
    {
        len = sUser.len;
        // Безпечне копіювання
        strng = new char[len + 1];
        strcpy(strng, sUser.strng);
 
    }
    Ryadok(const char s);// Конструктор, що приймає як параметр символ;
 
    ~Ryadok()// Деструктор;
    {
        delete[] strng;
    }
 
    int get_length()//  Метод для одержання довжини рядка;
    {
        len = strlen(strng);
        return len;
    }
    //void cleaning()// Метод для очищення рядок; 
    //{
    //  strng = NULL;
    //}
};
 
class RyadokIdentifier : public Ryadok {
 
public:
    RyadokIdentifier() : Ryadok()
    {
 
    }
    RyadokIdentifier(char *sUser) : Ryadok(sUser)
    {
 
    }
    RyadokIdentifier(const char s) : Ryadok(s)
    {
 
    }
    RyadokIdentifier(const RyadokIdentifier & sUser) : Ryadok(sUser)
    {
 
    }
    
    void RyadokIdentifier::Lowercase(char *sUser)
    {
        for (int i = 0; i <= len; i++)
            strng[i] = toupper(strng[i]);
        cout << strng << endl;
 
    }
    void RyadokIdentifier::Uppercase(char *sUser)
    {
        for (int i = 0; i <= len; i++)
            strng[i] = tolower(strng[i]);
        cout << strng << endl;
    }
    char* RyadokIdentifier::FirstOccurrence(char s)
    {
        char* i;
        i = strchr(strng, 's');
        return i;
    }
    RyadokIdentifier RyadokIdentifier::operator + (const RyadokIdentifier &str)
    {
        // створення тимчасового обєкта                           
        RyadokIdentifier sVar;
 
        // вираховуємо нову довжину стрічки
        sVar.len = len + str.len;
 
        // Виділяємо пам’ять під нову стрічку
        sVar.strng = new char[sVar.len + 1];
 
        //Ініціалізація другої частини стрічки
        strcat(sVar.strng, str.strng);
 
        //  Повернення нового обєкта        
        return sVar;
    }
 
    bool RyadokIdentifier::operator<(RyadokIdentifier &obj)
    {
        if (obj.strng[0] < strng[0]) return true;
        else return false;
 
    }
 
    bool RyadokIdentifier::operator>(RyadokIdentifier &obj)
    {
        if (obj.strng[0] > strng[0]) return true;
        else return false;
    }
 
    RyadokIdentifier &RyadokIdentifier::operator=(RyadokIdentifier &obj)
    {
        if (this == &obj) return *this;
        else
        {
            delete[] strng;
            strng = new char[(obj.strng[0] + 1)];
            int i;
            for (i = 0; i <= obj.strng[0]; i++) strng[i] = obj.strng[i];
            return *this;
        }
    }
    friend ostream &operator << (ostream &out, RyadokIdentifier &obj)
    {
        out << obj.strng << endl;
        return out;
    }
 
    friend istream &operator>> (istream &in, RyadokIdentifier &obj)
    {
        cout << ("Введите строку:  ");
        in >> obj.strng;
        return in;
    }
 
};
int main()
{
    RyadokIdentifier obj;
    char s;
    char * i;
    int len;
    Ryadok *ryad;  
    ryad = &obj;
    RyadokIdentifier A, B, C;
    cin >> A;
    cin >> A;
    cout << "Введіть символ" << endl;
    cin >> s;
    len = ryad->get_length();
    i = obj.FirstOccurrence(s);
    cout << "Довжина першого рядка" << i << "символів" << endl;
    C = A + B;
 
    cout << "Довжина першого рядка" << C << "символів" << endl;
 
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 08:30

2

Цитата
Сообщение от denbi00
Посмотреть сообщение

в чем причина

Если определяешь функцию-член внутри класса, то не надо перед ней писать RyadokIdentifier::.



0



Модератор

Эксперт С++

12641 / 10135 / 6102

Регистрация: 18.12.2011

Сообщений: 27,170

04.12.2015, 08:50

3

Это в принципе не запрещено — просто излишне.
У меня на VS 2008 компилируется без ошибок



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 12:27

4

Цитата
Сообщение от zss
Посмотреть сообщение

Это в принципе не запрещено — просто излишне.

Официальный документ с вами не согласен

В С++ qualifiсation можно использовать только для уже объявленных имен в классе или неймспейсе. Согласно параграфу 8.3

When the declaratorid is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers (or, in the case of a namespace, of an element of the inline namespace set of that namespace (7.3.1)) or to a specialization thereof; the member shall not merely have been introduced by a using-declaration in the scope of the class or namespace nominated by the nested-name-specifier of the declarator-id.



1



0 / 0 / 0

Регистрация: 21.11.2014

Сообщений: 11

04.12.2015, 14:04

 [ТС]

5

Этот код?

Добавлено через 28 минут
А эта ошибка 164 [Error] no match for ‘operator=’ in ‘C = RyadokIdentifier::operator+(const RyadokIdentifier&)((*(const RyadokIdentifier*)(& B)))’ ?



0



Tulosba

:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 14:35

6

Цитата
Сообщение от DrOffset
Посмотреть сообщение

В С++ qualifiсation можно использовать только для уже объявленных имен в классе или неймспейсе.

Т.е. следующий код должен быть валидным?

C++
1
2
3
4
namespace N {
    void f();
    void N::f() {}
}

Что-то не хочет:

error: explicit qualification in declaration of ‘void N::f()’



0



DrOffset

16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 15:59

7

Цитата
Сообщение от Tulosba
Посмотреть сообщение

Т.е. следующий код должен быть валидным?

Он валидный, но подразумевает не тот смысл, который ты вложил.
Смотри что получается:

C++
1
2
3
4
5
6
7
8
namespace N {
 
    namespace N { void f(); };
 
    void f();
 
    void N::f() {}
}



0



:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 16:09

8

DrOffset, ::N::N::f и ::N::f это разные сущности. При этом ::N::f остается не определена.

Из цитаты Стандарта я понял, что можно ссылаться с указанием квалификатора имени на член текущего (не вложенного) класса/пространства имен, а не какого-то другого. Если это действительно так, то хотелось бы увидеть рабочий пример. Если не так, то не помешало бы уточнения по цитате.



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 16:24

9

Собственно, если процитировать чуть дальше, об этом написано прямо.

When the declarator id is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers (or, in the case of a namespace, of an element of the inline namespace set of that namespace (7.3.1))

Добавлено через 3 минуты

Цитата
Сообщение от Tulosba
Посмотреть сообщение

это разные сущности.

Разные.

Цитата
Сообщение от Tulosba
Посмотреть сообщение

При этом ::N::f остается не определена.

Я лишь показал, чем является void N::f() {} в представленном тобой контексте. Причем это совершенно логично, даже без чтения стандарта.

Цитата
Сообщение от Tulosba
Посмотреть сообщение

Из цитаты Стандарта я понял, что можно ссылаться с указанием квалификатора имени на член текущего класса/пространства имен, а не какого-то другого.

Цитата выше.

Цитата
Сообщение от Tulosba
Посмотреть сообщение

Если не так, то не помешало бы уточнения по цитате.

Уточнение есть. Я его только что дал. А так, ты и сам мог бы озаботиться и дополнить



0



Tulosba

:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 16:37

10

DrOffset, так inline namespace это не nested namespace. Вот пример с inline:

C++
1
2
3
4
namespace N {
    inline namespace M { void f(); }
    void M::f() {}
}

Тут ::N::M::f и ::N::f по сути одно и то же, но с разными именами (именно из-за специфики inline).

Цитата
Сообщение от DrOffset
Посмотреть сообщение

Уточнение есть. Я его только что дал.

Т.е. для текущего класса/пространства имен всё же нельзя несмотря на:

Цитата
Сообщение от DrOffset
Посмотреть сообщение

qualifiсation можно использовать только для уже объявленных имен в классе или неймспейсе

?



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 17:42

11

Цитата
Сообщение от Tulosba
Посмотреть сообщение

inline namespace это не nested namespace.

Согласен — это не в тему.

Цитата
Сообщение от Tulosba
Посмотреть сообщение

Т.е. для текущего класса/пространства имен всё же нельзя несмотря на:

Однако, здесь все равно выводы верные выше. Т.к. в текущем пространстве имен — это будет означать квалификацию вложенного пространства имен в текущее. Т.е. определить в текущем пространстве имен квалифицированное на него же же имя — нельзя. И это не противоречит этому пункту нисколько.



0



Tulosba

:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 18:04

12

Цитата
Сообщение от DrOffset
Посмотреть сообщение

Т.е. определить в текущем пространстве имен квалифицированное на него же же имя — нельзя.

Ну и для класса получается аналогично? У ТС вариант как раз с классом. И по нему ты высказался:

Цитата
Сообщение от DrOffset
Посмотреть сообщение

В С++ qualifiсation можно использовать только для уже объявленных имен в классе или неймспейсе.

из чего, кстати, не следует невозможность сделать этого в текущем классе. Да и в цитате из Стандарта про текущий класс не сказано (не замечено мной).
Т.е. вроде как запись вида:

C++
1
2
3
4
struct S {
    void f(); // объявление 
    void S::f() {} // определение
};

должна быть валидной по крайней мере с точки зрения разрешения указания квалификатора имени. Однако получаем не только ошибку:

error: class member cannot be redeclared

но и

error: extra qualification on member ‘f’

Хотя последней, как я понимаю, быть не должно (было ведь объявление до определения).



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 18:26

13

Tulosba, скорее всего это все происходит потому, что у меня нет возможности внимательно посмотреть С++11 стандарт (это может занять значительное время), т.к они убрали из известного мне места эти формулировки в явном виде. Поэтому, если ты позволишь, я приведу цитату из С++03:
8.3

A declarator-id shall not be qualified except for the definition of a member function (9.3) or static data member (9.4) or nested class (9.7) outside of its class, the definition or explicit instantiation of a function, variable or class member of a namespace outside of its namespace, or the definition of a previously declared explicit specialization outside of its namespace, or the declaration of a friend function that is a member of another class or namespace (11.4).

При этом это «outside» проистекает как раз из логичности того, о чем я уже выше говорил. Такое указание синтаксически означало бы определение члена пространства имен или класса уже вложенного в текущий.



1



:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 19:19

14

Цитата
Сообщение от DrOffset
Посмотреть сообщение

убрали из известного мне места эти формулировки в явном виде

Вот нашел объяснение причины: http://wg21.cmeerw.net/cwg/issue482
Правда, не понял как продемонстрировать вот это заключение:

does allow a typedef declaration to use a qualified-id, which was not permitted before

Есть мысли на этот счет?



1



DrOffset

16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 20:17

15

Цитата
Сообщение от Tulosba
Посмотреть сообщение

Есть мысли на этот счет?

Пока нет. Надо подумать.
Они пошли по пути, который ты предлагал как вероятный.
В таком случае, если этот параграф действительно изменили (пока у меня не будет на руках законченной версии С++14 — я оставляю за собой право сомневаться), то ни один из компиляторов не ведет себя корректно в этом вопросе: clang в режиме С++98 все равно разрешает писать так:

C++
1
2
3
4
5
namespace A
{
    void foo();
    void A::foo();
};

хотя и не должен. А GCC во всех режимах это запрещает.
Очень жаль, что comeauonline больше не работает.



0



:)

Эксперт С++

4773 / 3267 / 497

Регистрация: 19.02.2013

Сообщений: 9,046

04.12.2015, 20:58

16

Цитата
Сообщение от DrOffset
Посмотреть сообщение

Очень жаль, что comeauonline больше не работает.

А там что ты хотел увидеть?



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.12.2015, 21:19

17

Цитата
Сообщение от Tulosba
Посмотреть сообщение

А там что ты хотел увидеть?

Посмотреть как это на практике учитывалось в самом продвинутом с точки зрения соответствия стандарту компиляторе



0



Содержание

  1. Ошибка «extra qualification» при компиляции gcc-4.1
  2. Re: Ошибка «extra qualification» при компиляции gcc-4.1
  3. Re: Ошибка «extra qualification» при компиляции gcc-4.1
  4. Re: Ошибка «extra qualification» при компиляции gcc-4.1
  5. Error extra qualification on member
  6. Error extra qualification on member
  7. Porting to gcc 4 (Warnings)
  8. Overview
  9. Dangerous compiler options
  10. gcc options -ftraditional and -ftraditional-cpp
  11. Analysis
  12. Solution
  13. gcc option -fpermissive
  14. Analysis
  15. Solution
  16. gcc option -mstrict-align
  17. Analysis
  18. Solution
  19. List of warnings
  20. warning: ‘XXX’ defined but not used
  21. Analysis
  22. Solution
  23. warning: deprecated conversion from string constant to ‘char*’
  24. Analysis
  25. Solution
  26. warning: extra qualification ‘XXX’ on member ‘YYY’
  27. Analysis
  28. Solution
  29. warning: pointer targets . differ in signedness
  30. Analysis
  31. Solution
  32. warning: there are no arguments to ‘XXX’.
  33. Analysis
  34. Solution
  35. warning: . discards qualifiers from pointer target type
  36. Analysis
  37. warning: unused variable ‘XXX’
  38. Analysis
  39. Other warning.
  40. note: obsolete option -I- used, please use -iquote instead
  41. Analysis
  42. Solution

Доброго времени суток, коллеги!

Недавно перешел на fedora core 5 (FC5), в которой установлен gcc-4.1, да и сам дистр содран именно этим компилятором. Но в процессе работы выяснилось, что многие пакеты программ не собираются gcc-4.1. Хотя gcc-4.0.2 еще собирались. У меня с основном вылазят ошибки пободные этой :
fitdataset.cpp:177: error: extra qualification ‘FITRasterBand::’ on member ‘FITRasterBand’
fitdataset.cpp: In static member function ‘static GDALDataset* FITDataset::Open(GDALOpenInfo*)’:
fitdataset.cpp:1019: warning: dereferencing type-punned pointer will break strict-aliasing rules
make[4]: *** [../o/fitdataset.o] Ошибка 1

и вот эта «extra qualification» довольно серезно достала. Возможно ли как нибудь пофиксить это? Мож есть заметный ключик к gcc-4.1, который обучит его вести себя как gcc-4.0.2? В инете предлагают фиксить каждую строчку, вызывающую аналогичную ошибку. Но, чуствую, строк таких немало. Я не программер, посему квалифицированно не могу обработать эту ситуацию.
Прошу помочь — надо край.

Спасибки!
Как я понял простого проблемы совместимости своего кода с gcc-4.1 должен решать сам разработчик. Потому как еслм всег несколько проблем, то можно решить самому. В моеи случае проект довольно большой и таких ошибок — море. Можно ли как-нибудь заставить gcc-4.1 работать в стиле gcc-4.0.2?

>Можно ли как-нибудь заставить gcc-4.1 работать в стиле gcc-4.0.2?

Нет, только следовать стандарту. Был еще портинггайд для gcc4.0 тоже рекомендую посмотреть. Вроде его гаврики из макинтошей нарисовали, по крайней мере мне гугль его там нашел.

А если хочется не мараться, то лучше компилять старым пока терпят. Ну и за компанию время протянуть, пока ошибки не исправите.

Источник

I keep getting the error extra qualification on member ‘Operator>’ and I don’t understand why. The error is with the statements below. I also tried changing it so that it just reads Employee2 operator>(Employee2& emp) but then it says it must have exactly 2 variables. Any help on this would be greatly appreciated.

bool Employee2::operator>(Employee2& emp); //in my header file

bool Employee2::operator>(Employee2& emp) //in my Employee2.cpp file
<
if(this->GetTotalEarned() > emp.GetTotalEarned())
<
cout this->GetTotalEarned())
<
cout GetTotalEarned())
<
cout Last edited on

sorry for the confusion, I’m still a little new to the forum but below is the full header code, most isn’t important to know but the
bool Employee2::operator>(Employee2& emp); that is giving me errors in in public.

#ifndef Employee2_H //Employee2_H
#define Employee2_H
#include

using namespace std;
class Employee2
<
public:
Employee2( unsigned int newID, string newLastName, string newFirstName, float newHourlyRate);
int GetID();
friend ostream& operator (Employee2& emp);
void SetID(int n);
string GetFirstName();
void SetFirstName(string str);
string GetLastName();
void SetLastName(string str);
float GetHourlyRate();
void SetHourlyRate(float n);
float Pay(float nHours);
float SalaryEarned( float nHours);
float GetTotalEarned();

private:
unsigned int ID;
string LastName;
string FirstName;
float HourlyRate;
float TotalEarned;
void increment();
>;

Источник

I am doing the example on dialogs from C++ gui programming with QT 4

I have finddialog.h
as
[code]
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;

class FindDialog : public QDialog
<
Q_OBJECT

public :
FindDialog(QWidget *parent = 0);

private slots:
void findClicked();
void enableFindButton(const QString &text);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *backwardCheckBox;
QPushButton *findButton;
QPushButton *closeButton;
#endif
[/code]

finddialog.cpp
[code]
#include
#include «finddialog.h»
FindDialog::FindDialog(QWidget *parent) : QDialog(parent)
<
label = new QLabel(tr(«Find &what:»));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);

QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(topLeftLayout);
leftLayout->addWidget(findButton);
leftLayout->addWidget(backwardCheckBox);

QVBoxLayout *rightLayout = new QVBoxLayout;
rightLayout->addLayout(leftLayout);
rightLayout->addLayout(rightLayout);
rightLayout->addStretch();

QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);

Источник

Porting to gcc 4 (Warnings)

Overview

The transition from gcc version 3.3.4 (as used until VLT2008) to gcc 4.x caused a row of problems with inconsistencies and incompatibilities in our code, as described in TWiki page «Porting to gcc 4 (Mandatory Changes for VLT2009)». That page describes only the errors preventing from compiling successfully.

In addition, a very large number of warnings occur, often obstructing the view of the serious errors. Just to give an idea: almost 50000 warnings were generated compiling the VLT Common Software, owing to the gcc change from version 3 to 4.

Some of these warnings give hints about deprecated functionality which will no longer be supported in future compiler versions. Some of these warnings are in fact errors forced into warnings by specific compiler options just to get the code to pass the compiler. Many of these warnings are due to a lower tolerance level towards deviations from the standard.

Dangerous compiler options

gcc options -ftraditional and -ftraditional-cpp

Analysis

Description of the option -traditional taken from the gcc manual (see attachment on Porting to gcc 4 (Mandatory Changes for VLT2009)):
-traditional: Formerly, these options caused GCC to attempt to emulate a pre-standard C compiler. They are now only supported with the ‘-E’ switch. The preprocessor continues to support a pre-standard mode. See the GNU CPP manual for details.
-traditional-cpp: Try to imitate the behavior of old-fashioned C preprocessors, as opposed to ISO C preprocessors.

Solution

The option -traditional has been removed form the vltMakefile .

gcc option -fpermissive

Analysis

Description of the option -fpermissive taken from the gcc manual (see attachment on Porting to gcc 4 (Mandatory Changes for VLT2009)):
-fpermissive: Downgrade some diagnostics about nonconforming code from errors to warnings. Thus, using ‘-fpermissive’ will allow some nonconforming code to compile.

The gcc manual discourages the usage of this option:
We do not recommend using ‘-fpermissive’ to work around invalid code, and it will also only catch cases where functions in base classes are called, not where variables in base classes are used (. ).

The option -fpermissive was added to the vltMakefile to cope with certain problems caused by stricter handling of the gcc compiler.

Solution

All concerned sources have been adapted to comply with the standard and the option -fpermissive removed from the VLT2009 vltMakefile .

One example for the usage of not standard-compliant code is the usage of a so called «extra qualification» in class definitions (see Warning: extra qualification on member).

gcc option -mstrict-align

Analysis

The compiler option -mstrict-align is not supported by older compiler versions, especially not by the gcc compiler used with VxWorks 5.5.

Solution

If LCU source code is to support both VxWorks version 5.5 and 6 the settings in vltMakefile must not use the gcc option -mstrict-align by default for all LCU sources. If this option is required in the vltMakefile then it has to be used in a case differentiation depending (explicitly or implicitly) on the used VxWorks version.

The vltMakefile has been updated and the settings now depend on the WIND_BASE value. For VxWorks version 5.5 the gcc option -mstrict-align is not used.

List of warnings

Here is a collection of warnings, extracted from the VLTSW integration and filtered for identifier name etc.

warning: ‘XXX’ defined but not used

Analysis

The majority of this problem’s occurrences is owed to the change in the rcsId handling ( warning: ‘rcsId’ defined but not used ) — see also Porting to gcc 4 (Mandatory Changes for VLT2009).
The automatic conversion could add the macro ATTRIBUTE_UNUSED only to all rcsId definitions where the file vltPort.h has been already included. In all other cases the decision whether to add the (missing) include file vltPort.h or otherwise the file vltAttrib.h must be taken by the developper.
A total of 140 files in the VLT Common Software is still affected.

Solution

Add include file vltPort.h or (if vltPort.h may not be used in specific cases) vltAttrib.h to all affected source files and add ATTRIBUTE_UNUSED to the rcsId definition.

warning: deprecated conversion from string constant to ‘char*’

Analysis

Building the VLTSW this warning occured over 5121 times in 326 files.

The warnings are due to declarations like: or

And for example the definition of rcsId, which appears 187 times:

Solution

All source code has to be aligned to comply with the standards. The way to fix this is to replace by const char pointers :

Ex: case rcsId : should be replaced by

However, the large number of ocurrences in the sources require an automated solution.

For the case of rcsId, the following sed command can be used:

Analysis

First a code example demonstrating the «extra qualification»: In this example the method YYY is defined with the preceding class name XXX:: thus specifying a superfluous «extra qualification».
The second method ZZZ is defined correctly.

gcc 4 does not permit this «extra qualification» any longer (in contrast to earlier compiler versions) and the compilation fails with the error message error: extra qualification ‘XXX’ on member ‘YYY’ .
However, the compiler can be forced to accept such non-conforming code by specifying the gcc option -fpermissive. Then the error is turned into a warning and the compilation does not fail.

Solution

Removing the «extra qualification» is an essential step to make the source code standard-compliant.

warning: pointer targets . differ in signedness

Analysis

The majority of these warning are produced by the usage of vltBYTES (defined as unsigned char in vltPortGeneral.h) where a char* is expected (see SPR VLTSW20080211).

logManager.c:284: warning: pointer targets in passing argument 1 of ‘strcpy’ differ in signedness

Solution

The following has been implemented to get rid of the warning :

  • type vltINT8 changed, defined now as signed char
  • type vltBYTES unchanged, defined as unsigned char
  • type vltSTRING, defined as char (see SPR VLTSW20090007), added

warning: there are no arguments to ‘XXX’.

warning: there are no arguments to ‘XXX’ that depend on a template parameter, so a declaration of ‘XXX’ must be available

Analysis

The problem is explained here:

In short, the C++ compiler now follows the C++ standard that prescribes that all names that are not dependent on template parameters are bound to their present definitions when parsing a template function or class.
Only names that are dependent are looked up at the point of instantiation.

Solution

In order to make it clear that you want the member of the base class, you need to defer lookup until instantiation time, at which the base class is known.

For this, you need to access i in a dependent context, by either using this->i (remember that this is of type Derived *, so is obviously dependent), or using Base ::i. Alternatively, Base ::i might be brought into scope by a using-declaration.

For example, if you get the warning on a line like:

Simply replace it with:

warning: . discards qualifiers from pointer target type

Analysis

This program attempts to modify constant data, and to discard the const property of the argument s in the return value.

warning: unused variable ‘XXX’

Analysis

In this program the variable i and the parameter p are never used.

Other warning.

The two following forms can appear :

  • warning: pasting «XXX» and «»: Command received»» does not give a valid preprocessing token
  • warning: pasting «XXX» and «»: Command executed»» does not give a valid preprocessing token
  • warning: assignment makes integer from pointer without a cast
  • warning: passing arg 2 of `XXX’ makes integer from pointer without a cast
  • warning: return makes integer from pointer without a cast
  • warning: assignment makes pointer from integer without a cast
  • warning: passing arg 1 of `XXX’ makes pointer from integer without a cast
  • warning: initialization makes pointer from integer without a cast
  • warning: passing argument 1 (2, 3, . ) of ‘XXX’ from incompatible pointer type

note: obsolete option -I- used, please use -iquote instead

Analysis

This message occurs in two slightly differing forms depending on the usage of the language C or C++:

  • cc1: note: obsolete option -I- used, please use -iquote instead
  • cc1plus: note: obsolete option -I- used, please use -iquote instead

In the vltMakefile the option -I- was added to force the compiler to always restart the search of include files from the beginning of the search path. The -iquote option is not a complete replacement for -I-. Without -I- there is no way to inhibit the use of the directory of the current file as the first search directory for #include «file».

see SPR VLTSW20080253 for more details

Solution

It has been decided for VLT2009 to keep the option -I- until it disappears. And the output of the compiler has been filtered with a grep to suppress the warning.

Источник

  • Forum
  • Beginners
  • extra qualification error in C++

extra qualification error in C++

have a member function that is defined as follows.

1
2
3
4
  const Time Time::operator+(const Time &other) { 
int hour = (*this).getHour() + other.getHour(); 
int min = (*this).getMinute() + other.getMinute(); 
int sec = (*this).getSecond()+ other.getSecond(); 

When I compile the source, I got

error: Date.cpp:16:12: error: extra qualification ‘Time::’ on member ‘operator+’ [-fpermissive] const Time Time::operator+(const Time &other) ;

What is this? How do I remove this error?

it run fine with Visual Studio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream> 
#include <iomanip> 

using std::cout; 
using std::setfill; 
using std::setw; 
using std::cin; 
using std::cout; 
using std::endl; 

class Time 
{ 
public: 
Time( int = 0, int = 0 ); 

const Time Time::operator+(const Time &other) ; 
void setTime( int, int); 
void setHour( int ); 
void setMinute( int ); 

int getHour() const; 
int getMinute() const; 

void Time::get( ); 
void Time::display(); 

private: 
int hour;
int minute; 
}; 

Time::Time( int hour, int minute ) 
{ 
setTime( hour, minute); 
} 

void Time::setTime( int hour, int minute ) 
{ 
setHour( hour ); 
setMinute( minute ); 
} 

void Time::get( ) 
{ 
int hour, minute, second; 
cout << "Enter hour : " ; 
cin >> hour; 
cout << endl ;	
cout << "Enter minute : " ; 
cin >> minute; 
cout << endl ;
setTime(hour,minute); 
} 

void Time::setHour( int h ) 
{ 
hour = h; 
} 

void Time::setMinute( int m ) 
{ 
minute = m; 
} 


int Time::getHour ( ) const 
{ 
return hour; 
} 

int Time::getMinute () const 
{ 
return minute; 
} 

void Time::display() 
{ 
cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) 
<< minute; 
} 


const Time Time::operator+(const Time &other) { 
int hour = (*this).getHour() + other.getHour(); 
int min = (*this).getMinute() + other.getMinute(); 

if ( min > 60 ) 
{ 
min = min - 60; 
hour = hour + 1; 
} 
if ( hour > 24 ) 
{ 
hour = hour - 24; 
} 
return Time( hour, min); 
} 


int main()
{

  Time tm(12,3);
  tm.display();
  int a;
  cin >>a;
  return 0;
}

line 16 — 19
and 83 -85

Last edited on

Learn to indent.

const Time Time::operator+(const Time &other) ; in line 16 is a declaration

1
2
3
class foo{
   //declarations go here
};

as you can see, it is obvious of which class the function is a member of, so there is no need to put `Time::’ in the declaration.

Also, I suppose that you actually tried to say Time operator+(const Time &other) const, that is `the function may be used with constant objects’

ok but how do u fix 83-85 line ?
if I tried to delete Date:: it will give me the error that (this*) is not compile

this is how Visual Studio say
1 IntelliSense: ‘this’ may only be used inside a nonstatic member function

and this is how g++ works

In file included from time.cpp:1:0:
Time.h:11:12: error: extra qualification ‘Time::’ on member ‘operator+’ [-fpermissive]
const Time Time::operator+(const Time &other) ;
^
Time.h:19:6: error: extra qualification ‘Time::’ on member ‘get’ [-fpermissive]
void Time::get( );
^
Time.h:20:6: error: extra qualification ‘Time::’ on member ‘display’ [-fpermissive]
void Time::display();
^

I told you already, remove the `Time::’ in the declarations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Time 
{ 
	public: 
		Time( int = 0, int = 0 ); 

		const Time operator+(const Time &other); 
		void setTime( int, int); 
		void setHour( int ); 
		void setMinute( int ); 

		int getHour() const; 
		int getMinute() const; 

		void get();  //declaration, no Time::
		void display(); 

	private: 
		int hour;
		int minute; 
}; 

//member function definition outside of class definition
//must say which class it belongs to
void Time::get( ) 
{ 
	int hour, minute, second; 
	cout << "Enter hour : " ; 
	cin >> hour; 
	cout << endl ;	
	cout << "Enter minute : " ; 
	cin >> minute; 
	cout << endl ;
	setTime(hour,minute); 
}

Topic archived. No new replies allowed.

I am doing the example on dialogs from C++ gui programming with QT 4

I have finddialog.h
as
[code]
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;

class FindDialog : public QDialog
{
Q_OBJECT

public :
FindDialog(QWidget *parent = 0);

signals:
void findNext(const QString &str,Qt::CaseSensitivity cs);
void findPrevious(const QString &str,Qt::CaseSensitivity cs);

private slots:
void findClicked();
void enableFindButton(const QString &text);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *backwardCheckBox;
QPushButton *findButton;
QPushButton *closeButton;
#endif
[/code]

finddialog.cpp
[code]
#include <QtGui>
#include «finddialog.h»
FindDialog::FindDialog(QWidget *parent) : QDialog(parent)
{
label = new QLabel(tr(«Find &what:»));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);

 caseCheckBox = new QCheckBox(tr("Match &case"));
 backwardCheckBox = new QCheckBox(tr("Search &backward"));
 
 findButton = new QPushButton(tr("&Find"));
 findButton->setDefault(true);
 findButton->setEnabled(false);
 closeButton = new QPushButton(tr("Close"));

connect(lineEdit,SIGNAL(textChanged(const QString &)),this,SLOT(enableFindButton(const QString &)));
connect(findButton,SIGNAL(clicked()),this,SLOT(findClicked()));
connect(closeButton,SIGNAL(clicked()),this,SLOT(close()));

QHBoxLayout *topLeftLayout = new QHBoxLayout;

topLeftLayout->addWidget(label);
topLeftLayout->addWidget(lineEdit);

QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(topLeftLayout);
leftLayout->addWidget(findButton);
leftLayout->addWidget(backwardCheckBox);

QVBoxLayout *rightLayout = new QVBoxLayout;
rightLayout->addLayout(leftLayout);
rightLayout->addLayout(rightLayout);
rightLayout->addStretch();

QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);

setWindowTitle(tr(«Find»));
setFixedHeight(sizeHint().height());
}

void FindDialog :: findClicked()
{
QString text = lineEdit->text();
Qt:: CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseSensitive
: Qt::CaseInsensitive;
if(backwardCheckBox->isChecked()) {
emit findPrevious(text,cs);
}
else{
emit findNext(text,cs);
}
}
void FindDialog :: enableFindButton(const QString &text)
{
findButton->setEnabled(!text.isEmpty());

}
}
[/code]

main.cpp
[code]
#include <QApplication>
#include «finddialog.h>
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
FindDialog *dialog = new FindDialog;
dialog->show();
return app.exec();
}
[/code]

[code]
utkarsh@utkarsh-laptop:~/programming/qt/dialog$ ls
dialog.pro finddialog.cpp finddialog.h main.cpp Makefile
utkarsh@utkarsh-laptop:~/programming/qt/dialog$ make
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. -I. -o finddialog.o finddialog.cpp
finddialog.cpp:3: error: extra qualification ‘FindDialog::’ on member ‘FindDialog’
finddialog.cpp:3: error: ‘FindDialog::FindDialog(QWidget*)’ cannot be overloaded
finddialog.h:14: error: with ‘FindDialog::FindDialog(QWidget*)’
finddialog.cpp:44: error: extra qualification ‘FindDialog::’ on member ‘findClicked’
finddialog.cpp:44: error: ‘void FindDialog::findClicked()’ cannot be overloaded
finddialog.h:21: error: with ‘void FindDialog::findClicked()’
finddialog.cpp:56: error: extra qualification ‘FindDialog::’ on member ‘enableFindButton’
finddialog.cpp:56: error: ‘void FindDialog::enableFindButton(const QString&)’ cannot be overloaded
finddialog.h:22: error: with ‘void FindDialog::enableFindButton(const QString&)’
finddialog.cpp:60: error: expected unqualified-id at end of input
make: *** [finddialog.o] Error 1
utkarsh@utkarsh-laptop:~/programming/qt/dialog$ nano finddialog.cpp
utkarsh@utkarsh-laptop:~/programming/qt/dialog$
[/code]


0

0

Доброго времени суток, коллеги!

Недавно перешел на fedora core 5 (FC5), в которой установлен gcc-4.1, да и сам дистр содран именно этим компилятором. Но в процессе работы выяснилось, что многие пакеты программ не собираются gcc-4.1. Хотя gcc-4.0.2 еще собирались. У меня с основном вылазят ошибки пободные этой :

fitdataset.cpp:177: error: extra qualification ‘FITRasterBand::’ on member ‘FITRasterBand’

fitdataset.cpp: In static member function ‘static GDALDataset* FITDataset::Open(GDALOpenInfo*)’:

fitdataset.cpp:1019: warning: dereferencing type-punned pointer will break strict-aliasing rules

make[4]: *** [../o/fitdataset.o] Ошибка 1

и вот эта «extra qualification» довольно серезно достала. Возможно ли как нибудь пофиксить это? Мож есть заметный ключик к gcc-4.1, который обучит его вести себя как gcc-4.0.2? В инете предлагают фиксить каждую строчку, вызывающую аналогичную ошибку. Но, чуствую, строк таких немало. Я не программер, посему квалифицированно не могу обработать эту ситуацию.

Прошу помочь — надо край.

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

error: extra qualification

error: extra qualification

(OP)

1 Feb 07 10:49

hi guys,

i am just updating form RH7.2 to FC6  sad

and i got this message whe trying to compile with gcc-c++ 4.1.1

       error: extra qualification ‘hd::socket::’ on member                 ‘connectionName’

may somebody tell me whats going on ?

i am not going to a lower version of gcc …

thanks in advance

hector

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Я студент C ++ 11 и у меня проблемы с дополнительной ошибкой квалификации.

У меня есть класс, объявленный в файле .h и реализация для логической функции в отдельном файле .cpp.

Определение класса выглядит следующим образом:

class Order{
std::string customer, product;
std::vector<std::string> itemList;

bool validName(std::string name);
bool isCustomerName(std::string name);
bool isProductName(std::string name);
bool isItemName(std::string name);

public:

Order(std::vector<std::string> line);
void print(){
void graph(std::ofstream os);
};//class Order

все функции реализованы в отдельном файле cpp, и я определил все функции следующим образом:

Order::Order(std::vector<std::string> line){

или же

bool Order::isCustomerName(std::string name){

Когда я пытаюсь скомпилировать файл cpp, появляется эта ошибка:

error: extra qualification ‘Order::’ on member ‘Order’ [-fpermissive]

После его поиска кажется, что это ошибка, связанная с использованием оператора области действия либо в определении класса в той же функции, либо каким-либо двойным использованием оператора области действия.

Я не инкапсулировал реализации в файле cpp в отдельном пространстве имен, и я включил только соответствующий файл .h для файла cpp. Может кто-нибудь дать мне небольшой толчок в том направлении, на которое мне нужно обратить внимание, чтобы решить эту проблему?

Спасибо


Это вершина файла cpp:

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include "order.h"

это пример функции из того же cpp:

bool Order::isProductName(std::string name){
if (name.size() > 0 && isalpha(name[0]))
return true;
return false; }

Приведенное выше определение класса — это буквально все, что есть в .h для класса Order.

вершина .h это:

#pragma once
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include "util.h"

0

Решение

У вас есть эта строка в вашем классе:

 void print(){

Я полагаю, ты имел в виду

 void print();

Из-за способа компиляции C ++, когда вы говорите #include "order.h" компилятор буквально копирует и вставляет содержимое order.h в ваш файл cpp. Таким образом, он видит, что вы открыли это определение функции для печати и объявили некоторые локальные функции внутри функции-члена print (расширение gcc), а затем в конце концов закройте функцию в строке, помеченной };//class Order, Это выглядит как конец определения класса, но на самом деле это конец вашей функции. Позже определения функций, которые находятся в вашем файле cpp, рассматриваются как находящиеся внутри тела класса, что приводит в замешательство компилятор.

0

Другие решения

Других решений пока нет …

Porting to gcc 4 (Warnings)

  • Overview
  • Dangerous compiler options
    • gcc options -ftraditional and -ftraditional-cpp
    • gcc option -fpermissive
    • gcc option -mstrict-align
  • List of warnings
    • warning: ‘XXX’ defined but not used
    • warning: deprecated conversion from string constant to ‘char*’
    • warning: extra qualification ‘XXX’ on member ‘YYY’
    • warning: pointer targets … differ in signedness
    • warning: there are no arguments to ‘XXX’….
    • warning: … discards qualifiers from pointer target type
    • warning: unused variable ‘XXX’
    • Other warning…
    • note: obsolete option -I- used, please use -iquote instead

Overview

The transition from gcc version 3.3.4 (as used until VLT2008) to gcc 4.x caused a row of problems with inconsistencies and incompatibilities in our code, as described in TWiki page «Porting to gcc 4 (Mandatory Changes for VLT2009)». That page describes only the errors preventing from compiling successfully.

In addition, a very large number of warnings occur, often obstructing the view of the serious errors. Just to give an idea: almost 50000 warnings were generated compiling the VLT Common Software, owing to the gcc change from version 3 to 4.

Some of these warnings give hints about deprecated functionality which will no longer be supported in future compiler versions. Some of these warnings are in fact errors forced into warnings by specific compiler options just to get the code to pass the compiler. Many of these warnings are due to a lower tolerance level towards deviations from the standard.

Dangerous compiler options

gcc options -ftraditional and -ftraditional-cpp

Analysis

Description of the option -traditional taken from the gcc manual (see attachment on Porting to gcc 4 (Mandatory Changes for VLT2009)):
-traditional: Formerly, these options caused GCC to attempt to emulate a pre-standard C compiler. They are now only supported with the ‘-E’ switch. The preprocessor continues to support a pre-standard mode. See the GNU CPP manual for details.
-traditional-cpp: Try to imitate the behavior of old-fashioned C preprocessors, as opposed to ISO C preprocessors.

Solution

The option -traditional has been removed form the vltMakefile.

gcc option -fpermissive

Analysis

Description of the option -fpermissive taken from the gcc manual (see attachment on Porting to gcc 4 (Mandatory Changes for VLT2009)):
-fpermissive: Downgrade some diagnostics about nonconforming code from errors to warnings. Thus, using ‘-fpermissive’ will allow some nonconforming code to compile.

The gcc manual discourages the usage of this option:
We do not recommend using ‘-fpermissive’ to work around invalid code, and it will also only catch cases where functions in base classes are called, not where variables in base classes are used (…).

The option -fpermissive was added to the vltMakefile to cope with certain problems caused by stricter handling of the gcc compiler.

Solution

All concerned sources have been adapted to comply with the standard and the option -fpermissive removed from the VLT2009 vltMakefile.

One example for the usage of not standard-compliant code is the usage of a so called «extra qualification» in class definitions (see Warning: extra qualification on member).

gcc option -mstrict-align

Analysis

The compiler option -mstrict-align is not supported by older compiler versions, especially not by the gcc compiler used with VxWorks 5.5.

Solution

If LCU source code is to support both VxWorks version 5.5 and 6 the settings in vltMakefile must not use the gcc option -mstrict-align by default for all LCU sources. If this option is required in the vltMakefile then it has to be used in a case differentiation depending (explicitly or implicitly) on the used VxWorks version.

The vltMakefile has been updated and the settings now depend on the WIND_BASE value. For VxWorks version 5.5 the gcc option -mstrict-align is not used.

List of warnings

Here is a collection of warnings, extracted from the VLTSW integration and filtered for identifier name etc.

warning: ‘XXX’ defined but not used

Analysis

The majority of this problem’s occurrences is owed to the change in the rcsId handling ( warning: 'rcsId' defined but not used) — see also Porting to gcc 4 (Mandatory Changes for VLT2009).
The automatic conversion could add the macro ATTRIBUTE_UNUSED only to all rcsId definitions where the file vltPort.h has been already included. In all other cases the decision whether to add the (missing) include file vltPort.h or otherwise the file vltAttrib.h must be taken by the developper.
A total of 140 files in the VLT Common Software is still affected.

Solution

Add include file vltPort.h or (if vltPort.h may not be used in specific cases) vltAttrib.h to all affected source files and add ATTRIBUTE_UNUSED to the rcsId definition.

warning: deprecated conversion from string constant to ‘char*’

Analysis

Building the VLTSW this warning occured over 5121 times in 326 files.

The warnings are due to declarations like:

  char *aVar = "aString";

or

  void aFunc( char *aVar) { ... }
  aFunc( "aString" ); 

And for example the definition of rcsId, which appears 187 times:

ATTRIBUTE_UNUSED static char *rcsId="@(#) $Id: ...";

Solution

All source code has to be aligned to comply with the standards. The way to fix this is to replace by const char pointers :

const char *aVar = "aString";

or

void aFunc( const char *aVar) { ... } 
 

Ex: case rcsId :

ATTRIBUTE_UNUSED static char *rcsId="@(#) $Id: ...";

should be replaced by

ATTRIBUTE_UNUSED static const char *rcsId="@(#) $Id: ..."; 

However, the large number of ocurrences in the sources require an automated solution.

For the case of rcsId, the following sed command can be used:

find . -name "*.C"  -exec sed -i -e 's/ATTRIBUTE_UNUSED static char *rcsId/ATTRIBUTE_UNUSED static const char *rcsId/' {} ;

warning: extra qualification ‘XXX’ on member ‘YYY’

Analysis

First a code example demonstrating the «extra qualification»:

class XXX {
   int XXX::YYY(int parameter);
   int ZZZ(int parameter);
}

In this example the method YYY is defined with the preceding class name XXX:: thus specifying a superfluous «extra qualification».
The second method ZZZ is defined correctly.

gcc 4 does not permit this «extra qualification» any longer (in contrast to earlier compiler versions) and the compilation fails with the error message error: extra qualification 'XXX' on member 'YYY'.
However, the compiler can be forced to accept such non-conforming code by specifying the gcc option -fpermissive. Then the error is turned into a warning and the compilation does not fail.

Solution

Removing the «extra qualification» is an essential step to make the source code standard-compliant.

warning: pointer targets … differ in signedness

Analysis

There were 2532 warnings of this type, in different forms:

  • warning: pointer targets in assignment differ in signedness
  • warning: pointer targets in initialization differ in signedness
  • warning: pointer targets in passing argument 1 (2, 3, 4, 5, 6, 7, 8) of ‘XXX’ differ in signedness

The majority of these warning are produced by the usage of vltBYTES (defined as unsigned char in vltPortGeneral.h) where a char* is expected (see SPR VLTSW20080211).

For example:

logManager.c:284: warning: pointer targets in passing argument 1 of ‘strcpy’ differ in signedness

Solution

The following has been implemented to get rid of the warning :

  • type vltINT8 changed, defined now as signed char
  • type vltBYTES unchanged, defined as unsigned char
  • type vltSTRING, defined as char (see SPR VLTSW20090007), added

warning: there are no arguments to ‘XXX’….

Complete message:

warning: there are no arguments to ‘XXX’ that depend on a template parameter, so a declaration of ‘XXX’ must be available

Analysis

The problem is explained here:

http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html

In short, the C++ compiler now follows the C++ standard that prescribes that all names that are not dependent on template parameters are bound to their present definitions when parsing a template function or class.
Only names that are dependent are looked up at the point of instantiation.

Solution

In order to make it clear that you want the member of the base class, you need to defer lookup until instantiation time, at which the base class is known.

For this, you need to access i in a dependent context, by either using this->i (remember that this is of type Derived*, so is obviously dependent), or using Base::i. Alternatively, Base::i might be brought into scope by a using-declaration.

For example, if you get the warning on a line like:

   ErrAdd(tcsMOD, tcsERR_FATAL, __FILE_LINE__,  "cannot initialize");  

Simply replace it with:

   this->ErrAdd(tcsMOD, tcsERR_FATAL, __FILE_LINE__, "cannot initialize%);  

warning: … discards qualifiers from pointer target type

Different forms:

  • warning: passing arg 1 of `XXX’ discards qualifiers from pointer target type
  • warning: assignment discards qualifiers from pointer target type

Analysis

These warnings occur when a pointer is used incorrectly, violating a type qualifier such as const. Data accessed through a pointer marked as const should not be modified, and the pointer itself can only be assigned to other pointers that are also marked const.

Example:

char *
f (const char *s)
{
  *s = '';  /* assigns to read-only data */
  return s;   /* discards const */
}

This program attempts to modify constant data, and to discard the const property of the argument s in the return value.

warning: unused variable ‘XXX’

Analysis

These warnings indicate that a variable has been declared as a local variable or in the parameters of a function, but has not been used anywhere. An unused variable can be the result of a programming error, such as accidentally using the name of a different variable in place of the intended one. Example:

int
foo (int k, char * p)
{
  int i, j;
  j = k;
  return j;
}

In this program the variable i and the parameter p are never used.

Other warning…

 
warning: pasting "XXX" and "YYY" does not give a valid preprocessing token 

The two following forms can appear :

  • warning: pasting «XXX» and «»: Command received»» does not give a valid preprocessing token
  • warning: pasting «XXX» and «»: Command executed»» does not give a valid preprocessing token
   
warning: 'XXX' may be used uninitialized in this function  

warning: 'XXX' might be used uninitialized in this function  

warning: implicit declaration of function 'XXX'  

warning: incompatible implicit declaration of built-in function 'XXX'  

warning: the `XXX' function is dangerous and should not be used.  

warning: the use of `XXX' is dangerous, better use `YYY'  

warning: ... makes integer from pointer without a cast

Different forms:

  • warning: assignment makes integer from pointer without a cast
  • warning: passing arg 2 of `XXX’ makes integer from pointer without a cast
  • warning: return makes integer from pointer without a cast
warning: ... makes pointer from integer without a cast

Different forms:

  • warning: assignment makes pointer from integer without a cast
  • warning: passing arg 1 of `XXX’ makes pointer from integer without a cast
  • warning: initialization makes pointer from integer without a cast
warning: dereferencing type-punned pointer will break strict-aliasing rules  

warning: cast from pointer to integer of different size  

warning: comparison between pointer and integer  

warning: comparison is always false due to limited range of data type  

warning: comparison with string literal results in unspecified behaviour  

warning: data definition has no type or storage class  

warning: "__FILE_LINE__" redefined  

warning: double format, void arg (arg 3)  

warning: extra tokens at end of #endif directive  

warning: format '%ld' expects type 'long int', but argument 3 has type 'unsigned int'  

warning: int format, void arg (arg 3)  

warning: missing braces around initializer for 'XXX'  

warning: no semicolon at end of struct or union  

warning: passing arg 1 (2, 3, ...) of `XXX' from incompatible pointer type

Other form:

  • warning: passing argument 1 (2, 3, …) of ‘XXX’ from incompatible pointer type
warning: subscript has type `XXX'  

warning: this is the location of the previous definition 

warning: type defaults to `XXX' in declaration of `YYY'  

warning: use of cast expressions as lvalues is deprecated  

warning: suggest parentheses around assignment used as truth value  

warning: non-local variable 'argList [28]' uses anonymous type  

warning: ignoring old commands for target `test'  

warning: overriding commands for target `test'  

warning: return type of 'main' is not 'int'  

warning: (near initialization for `XXX[X].argument.X')  

warning: after previous specification in 'XXX'  

warning: default argument given for parameter 4 of 'XXX'  

warning: dereferencing 'void *' pointer  

warning: null character(s) ignored  

warning: overflow in implicit constant conversion  

warning: suggest explicit braces to avoid ambiguous `else' 

warning: 'return' with a value, in function returning void

note: obsolete option -I- used, please use -iquote instead

Analysis

This message occurs in two slightly differing forms depending on the usage of the language C or C++:

  • cc1: note: obsolete option -I- used, please use -iquote instead
  • cc1plus: note: obsolete option -I- used, please use -iquote instead

In the vltMakefile the option -I- was added to force the compiler to always restart the search of include files from the beginning of the search path. The -iquote option is not a complete replacement for -I-. Without -I- there is no way to inhibit the use of the directory of the current file as the first search directory for #include «file».

see SPR VLTSW20080253 for more details

Solution

It has been decided for VLT2009 to keep the option -I- until it disappears. And the output of the compiler has been filtered with a grep to suppress the warning.

— PeterKratzer — 23 Sep 2008

Понравилась статья? Поделить с друзьями:
  • Error extension manager init failed status 193 zxp installer
  • Error expression or statement is incorrect possibly unbalanced or
  • Error expression must have pointer to object type
  • Error expression must have integral or unscoped enum type
  • Error expression in new declarator must have integral or enumeration type