не компилится элементарный код
Модератор: Модераторы разделов
-
luncher
- Сообщения: 84
- ОС: mandriva 2008 spring
не компилится элементарный код
вот код:
Код: Выделить всё
# include <stdlib.h>
# include <math.h>
# include <iostream>
int plus(int, int);
main()
{
//using namespace std;
int sum,x=2,y=3;
//cin >> x;
//cin >> y;
plus(x,y);
std::cout << sum << std::endl;
}
int plus(int a, int b)
{
int a, b, sum;
sum=a*b;
return sum;
}
компилю в linux в g++
говорит:
prog3.cpp: In function ‘int plus(int, int)’:
prog3.cpp:18: ошибка: declaration of ‘int a’ shadows a parameter
prog3.cpp:18: ошибка: declaration of ‘int b’ shadows a parameter
раньше не сталкивался с такими ошибками, не понимаю как исправить, обьясните пожайлуста в чем ошибка и как с нею бороться!
-
serzh-z
- Бывший модератор
- Сообщения: 8256
- Статус: Маньяк
- ОС: Arch, Fedora, Ubuntu
- Контактная информация:
Re: не компилится элементарный код
Сообщение
serzh-z » 14.07.2009 16:18
luncher писал(а): ↑
14.07.2009 16:06
prog3.cpp:18: ошибка: declaration of ‘int a’ shadows a parameter
Объявления локлаьных «a» и «b» скрывает параметры функции… Как обращаться к аргументу функции «a», если на стеке объявлена локальная переменная с таким же именем?
-
Rootlexx
- Бывший модератор
- Сообщения: 4439
- Статус: GNU generation
- ОС: Debian GNU/Linux
Re: не компилится элементарный код
Сообщение
Rootlexx » 14.07.2009 16:20
luncher писал(а): ↑
14.07.2009 16:06
int plus(int a, int b)
luncher писал(а): ↑
14.07.2009 16:06
int a, b
Переменные a и b уже определены в объявлении функции. Сообщение об ошибке ясно об этом говорит:
luncher писал(а): ↑
14.07.2009 16:06
ошибка: declaration of ‘int a’ shadows a parameter
Вольный перевод: «объявление ‘int a’ перекрывает (затеняет, скрывает) параметр функции».
-
luncher
- Сообщения: 84
- ОС: mandriva 2008 spring
Re: не компилится элементарный код
Сообщение
luncher » 14.07.2009 16:32
спасибо за то что наставили дурака на путь истинный
теперь все компилится, действительно глупая ошибка
только старнно что при каждом запуске программы переменная sum получается каждые раз разной, огромной и отрицательной
-
fbi
- Сообщения: 34
Re: не компилится элементарный код
Сообщение
fbi » 14.07.2009 16:45
Ну а какой она ещё будет, если вы её ни чем не инициализируете, и ни чего ей не присваиваете:
main()
{
//using namespace std;
int sum,x=2,y=3;
//cin >> x ;
//cin >> y ;
plus(x,y);
std::cout << sum << std::endl;
}
sum = plus(x,y);
-
luncher
- Сообщения: 84
- ОС: mandriva 2008 spring
Re: не компилится элементарный код
Сообщение
luncher » 14.07.2009 18:10
fbi писал(а): ↑
14.07.2009 16:45
Ну а какой она ещё будет, если вы её ни чем не инициализируете, и ни чего ей не присваиваете:
main()
{
//using namespace std;
int sum,x=2,y=3;
//cin >> x ;
//cin >> y ;
plus(x,y);
std::cout << sum << std::endl;
}sum = plus(x,y);
спасибо, чето я сегодня особенно туплю
- Access Specifiers in C++
Declaration Shadows a Parameter
Error in C++
There are always some boundaries, ranges, or scope of every object or variable to access other class members like data members or member functions defined by access specifiers in C++ as public
, private
, or protected
.
When we define a variable more than once with the same names in the specific scope or block of the program, the compilers confused and throw’s an error saying a declaration shadows a parameter
.
Access Specifiers in C++
Before going into the details of the shadow parameter, it’s important to understand access specifiers. Generally, three access specifiers are public
, private
, and protected
.
Public Access Specifier in C++
A Public
specifier makes all the members (Data members or member functions) of a class public, which can be accessed throughout the program from other classes; you can directly access those member functions using the dot .
operator with the object of that same class.
#include<iostream>
using namespace std;
// class definition
class Cal_Circle{
public: // Public access specifier
double radius;
double compute_area(){
return 3.14*radius*radius;
}
};
// main function
int main(){
Cal_Circle obj;
// accessing public datamember outside class
obj.radius = 3.4;
cout << "Radius of the circle is: " << obj.radius << "n";
cout << "Area of the circle is: " << obj.compute_area();
return 0;
}
Output:
Radius of the circle is: 3.4
Area of the circle is: 36.2984
Private Access Specifier in C++
Private
access specifier keeps every member, either data member or member function, private within the boundaries of a class. They cannot be accessed outside of the class directly by the object of that class.
They are hidden from access outside the class to ensure the program’s security.
#include<iostream>
using namespace std;
// class definition
class Cal_Circle{
private: // private access specifier
double radius;
double compute_area(){
return 3.14*radius*radius;
}
};
// main function
int main(){
Cal_Circle obj;
// accessing public datamember outside class
obj.radius = 3.4;
cout << "Radius of the circle is: " << obj.radius << "n";
cout << "Area of the circle is: " << obj.compute_area();
return 0;
}
Output:
error: 'double Cal_Circle::radius' is private within this context
obj.radius = 3.4;
note: declared private here
double radius;
note: declared private here
double compute_area(){
See in this example, we have used the accessed specifier as private
and accessed it through the object of the class from the main function. And it’s throwing an error for each class member that is declared protected here.
Protected Access Specifier in C++
Similarly, the Protected
access specifier cannot be accessed outside of its class directly through the object of that class, but the difference is that the Protected
class or members can be accessed through derive class.
Using the object of the derived class, you can access the protected members of a class.
#include<iostream>
using namespace std;
class Radius{ // Base class
protected: // protected access specifier
double radius;
};
class Cal_Circle : public Radius { // Derive class
public: // private access specifier
double compute_area(int a){
radius = a;
return 3.14*radius*radius;
}
};
// main function
int main(){
Cal_Circle obj;
// accessing public datamember outside class
cout << "Area of the circle is: " << obj.compute_area(3);
return 0;
}
Output:
Area of the circle is: 28.26
Our base class is protected and has one data member radius
. We have inherited that base class to Cal_Circle
, and with the object of the derived class, we are accessing the protected data member radius
.
We are indirectly accessing the protected members of a protected class.
Declaration Shadows a Parameter
Error in C++
In computer programming, there are certain boundaries known as scope. This could be an if-else
block, a function, or a class.
A variable defined inside an if-else
block, function, or a class cannot be used unless and until you have defined it as public
. And a public variable, function, or class can be accessed throughout the program.
Also, it is prohibited in C++ to define one variable two times or more within a specific scope. And when you do it, an error is thrown as a declaration shadows a parameter
.
Let’s understand it through an example.
#include <iostream>
int doublenumber();
using namespace std;
int doublenumber(int x){
int x; // We are redefining the same variable as the parameter of the function
return 2 * x;
cout << endl;
}
int main(){ //Main function
int a;
cout << "Enter the number that you want to double it : " << endl;
cin >> a;
int d = doublenumber(a);
cout << "Double : " << d << endl;
return 0;
}
Output:
Test.cpp: In function 'int doublenumber(int)':
Test.cpp:6:9: error: declaration of 'int x' shadows a parameter
int x;
As we have seen, we cannot define one variable more than once in a specific block of code like function, class, and an if-else
block.
In the doublenumber()
function, we have a parameter int x
, and in the scope of this function, we are also defining another local int x
, which is shadowing the parameter and throwing an error.
2 / 1 / 4
Регистрация: 21.04.2018
Сообщений: 204
1
04.06.2018, 09:58. Показов 2546. Ответов 2
[Error] declaration of ‘olimp IGRU []’ shadows a parameter
Ругается в этом месте
C | ||
|
Вот сам код:
C | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
I am writing a program to calculate the users age (in days).
(P.S. PLEASE don’t make fun of my code, I know that it’s not pretty, or perfect, or (most likely) efficient)
|
|
Возьмите параметр конструктора с тем же идентификатором, что и элемент данных, который он инициализирует. Если они используются внутри списка инициализации, это будет считаться безопасным, и «затенение» не произойдет.
Однако возьмем следующий пример:
struct A{
A(int a, int b);
int a, b;
};
A::A(int a, int b)
: a(a)
, b(b)
{}
int main(){}
предупреждения, видимые с g ++:
g++ -Wshadow --std=c++1z -o main main.cpp
main.cpp: In constructor ‘A::A(int, int)’:
main.cpp:8:18: warning: declaration of ‘b’ shadows a member of ‘A’ [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:10: note: shadowed declaration is here
int a, b;
^
main.cpp:8:18: warning: declaration of ‘a’ shadows a member of ‘A’ [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:7: note: shadowed declaration is here
int a, b;
предупреждения, увиденные с лязгом:
clang++ -Wshadow --std=c++1z -o main t.cpp
main.cpp:8:10: warning: declaration shadows a field of 'A' [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:7: note: previous declaration is here
int a, b;
^
main.cpp:8:17: warning: declaration shadows a field of 'A' [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:10: note: previous declaration is here
int a, b;
Я ничего не делаю с членами данных в теле конструктора — так почему я получаю эти предупреждения?
Я хотел бы оставить флаг предупреждения включенным, чтобы поймать законные ошибки, но эти конкретные случаи вызывают слишком много ложного шума. Есть ли обоснованность в этих предупреждениях?
5
Решение
Хотя ты ничего не делаешь там, где может причинить тебе боль сейчас, Вы настраиваете себя на некоторые головные боли обслуживания.
Если сопровождающий Джо придет и ему нужно будет внести изменения следующим образом:
A::A(int a, int b)
: a(a)
, b(b)
{
storeReference(a);
}
К сожалению! Он просто хранит ссылку на параметр, а не на элемент данных.
Компилятор не говорит вам, что вы делаете что-то не так, по сути, он говорит вам, что вы, возможно, захотите изменить свои имена, чтобы у вас не было проблем в будущем.
Я бы, например, рекомендовал бы выбрать соглашение об именах для устранения неоднозначности и придерживаться его. Лично мне нравится ставить m_
в начале данных участника, но другие предпочитают суффикс _
к данным члена или конструктору param.
13
Другие решения
Жалуется из-за a(a)
а также b(b)
— имя члена структуры должно отличаться от имени параметра для конструктора. Тогда конструкция будет выглядеть mA(a)
а также mB(b)
-3
Aguilar, James
-
#1
Hey all. I was making a newbie mistake that I eventually figured out. That
is not my question. My question is about the error message. So let me set
the stage for you:
class Superclass
{
public:
Superclass(int);
}
class Subclass : public Superclass
{
public:
Subclass(int);
}
As you all surely know, the way to declare the constructor of subclass so
that it uses that of superclass is
Subclass::Subclass(int x)
: Superclass(x)
{ . . . }
As a newbie who comes from a Java background, I somehow managed to miss this
colon initializer notation in my text (B.Stoustrup or however you spell it).
So I was writing it as any Java newbie would:
Subclass::Subclass(int x)
{ Superclass::Superclass(x); . . . }
The real question, though, is why the heck can’t the error message be more
useful:
«Error: declaration of x shadows parameter»
What in the world does that mean? What is «shadowing» a parameter. And
where do I declare something that does so? As far as I can see, the
parameter itself is the only declaration of any kind. This is from g++ for
Cygwin, whatever the most recent version is.
Yours,
James
Advertisements
Rob Williscroft
-
#2
Aguilar, James wrote in in
comp.lang.c++:
Subclass::Subclass(int x)
{ Superclass::Superclass(x); . . . }The real question, though, is why the heck can’t the error message be
more useful:«Error: declaration of x shadows parameter»
It is useful, its telling you what is *really* wrong with your code.
What in the world does that mean? What is «shadowing» a parameter.
In C++ there is a rule:
If some thing can be parsed as a declaration it is.
In this case «Superclass::Superclass» is type and the brackets around
the «x» don’t matter, its as if you wrote:
Superclass x;
I.e declared a local variable x of type Superclass. It «shadows» the
paramiter declaration «int x».
And where do I declare something that does so? As far as I can see,
the parameter itself is the only declaration of any kind. This is
from g++ for Cygwin, whatever the most recent version is.
The error you got was nothing to do with not knowing how to invoke
base class constructors. It was about not knowing the declaration
rules for C++.
Its an unfortunate fact that often error messages don’t reflect
the *real* problem, but some (possibly unrelated) side effect
of that which we did wrong.
HTH.
Rob.
Rolf Magnus
-
#3
Hey all. I was making a newbie mistake that I eventually figured out.
That is not my question. My question is about the error message. So
let me set the stage for you:class Superclass
{
public:
Superclass(int);
}class Subclass : public Superclass
{
public:
Subclass(int);
}As you all surely know, the way to declare the constructor of subclass
so that it uses that of superclass isSubclass::Subclass(int x)
: Superclass(x)
{ . . . }As a newbie who comes from a Java background, I somehow managed to
miss this colon initializer notation in my text (B.Stoustrup or
however you spell it). So I was writing it as any Java newbie would:Subclass::Subclass(int x)
{ Superclass::Superclass(x); . . . }The real question, though, is why the heck can’t the error message be
more useful:
Because the compiler only sees what you wrote, not what you intended.
«Error: declaration of x shadows parameter»
What in the world does that mean? What is «shadowing» a parameter.
It means that you declare something with the same name as the parameter
and so you cannot use that name to accesss the parameter anymore, like:
void foo(int x)
{
int x;
// now the local x shadows the parameter x
}
And where do I declare something that does so?
Superclass::Superclass(x);
is the same as:
Superclass (x);
and the same as:
Superclass x;
As far as I can see, the parameter itself is the only declaration of
any kind.
It’s not a parameter. It’s a local variable.
Advertisements
Peter Ammon
-
#4
Hey all. I was making a newbie mistake that I eventually figured out. That
is not my question. My question is about the error message. So let me set
the stage for you:class Superclass
{
public:
Superclass(int);
}class Subclass : public Superclass
{
public:
Subclass(int);
}
Don’t forget the semicolons after the class declarations.
As you all surely know, the way to declare the constructor of subclass so
that it uses that of superclass isSubclass::Subclass(int x)
: Superclass(x)
{ . . . }As a newbie who comes from a Java background, I somehow managed to miss this
colon initializer notation in my text (B.Stoustrup or however you spell it).
So I was writing it as any Java newbie would:Subclass::Subclass(int x)
{ Superclass::Superclass(x); . . . }The real question, though, is why the heck can’t the error message be more
useful:
The code is erroneous, but not for the reason you expect.
Note that Superclass is certainly within the Superclass scope that you
specify with the scope resolution operator ::. So
Superclass::Superclass refers to the class Superclass. Then note that
the grammar permits declarators to be surrounded by parenthesis. So IOW,
Superclass::Superclass(x);
just means
Superclass x;
so you’re defining an instance of Superclass in the constructor with
identifier x, which would ordinarily be fine. However, there’s a
parameter with the same identifier, and since they have the same scope
(more or less) you get the error:
«Error: declaration of x shadows parameter»
[…]
-Peter