There are mainly 2 problems in your code, first, you are confusing static and non-static member variables and second, your last 3 functions are declared in the class declaration but you didn’t qualify them with Product::
so they are free standing functions with the same names. If you intended them to be the definitions of the members, qualify them.
To fix the first point, when you have a class like the following:
struct some_class
{
int nonstatic_member;
static int static_member;
}
You access the static ones using the TypeName::MemberName
syntax:
some_class::static_member = 5;
However, when a member is not static, you need an instance of that class to access the member:
some_class some_object;
some_object.nonstatic_member = 10;
The same rules apply for member functions as well:
void some_class::some_function()
{
some_class::nonstatic_member = 10; // error
this->nonstatic_member = 10; // fine
nonstatic_member = 10; // fine
static_member = 5; // fine
some_class::static_member = 5; // fine
}
Since none of your member variables are static, your use of Product::
everywhere is the cause of the second error.
If you’re not sure about the static member concept, here is a read: http://en.cppreference.com/w/cpp/language/static
I think I have been working on this code too long. Anyway here is whats happening.
header file (scope of the project forbids changing public)
#ifndef FRACTION_
#define FRACTION_
using namespace std;
#include <iostream>
class Fraction
{
private:
int num,denom;
public:
// Construct fraction from numerator and denominator
//
Fraction( int = 0, int = 1 );
// Construct fraction by copying existing fraction
//
Fraction( const Fraction& );
// Assign into fraction by copying existing fraction
//
Fraction& operator=( const Fraction& );
// Return true if fraction is valid (non-zero denominator)
//
bool IsValid() const;
// Return value of numerator
//
int Numerator() const;
// Return value of denominator
//
int Denominator() const;
// Input/Output operations
//
friend istream& operator>>( istream&, Fraction& );
friend ostream& operator<<( ostream&, const Fraction& );
};
// Comparative operations
//
bool operator==( const Fraction&, const Fraction& );
bool operator!=( const Fraction&, const Fraction& );
bool operator< ( const Fraction&, const Fraction& );
bool operator<=( const Fraction&, const Fraction& );
bool operator> ( const Fraction&, const Fraction& );
bool operator>=( const Fraction&, const Fraction& );
// Arithmetic operations
//
Fraction operator+( const Fraction&, const Fraction& );
Fraction operator-( const Fraction&, const Fraction& );
Fraction operator*( const Fraction&, const Fraction& );
Fraction operator/( const Fraction&, const Fraction& );
#endif
I am trying to overload the + operator, here is my code for that:
Fraction operator+(const Fraction &f1, const Fraction &f2)
{
return(((f1.num*f2.denom)+(f1.denom*f2.num)),(f1.denom*f2.denom));
}
I get an error about referencing num and denom as private variable, I am just having a hard time figuring out how to correct that problem.
Code for other’s reference:
#include <time.h> #include <cereal/access.hpp> class SimpleClass { public: explicit SimpleClass(struct tm const &); private: struct tm date; SimpleClass(); friend class MyCoolClass; friend class cereal::access; }; class MyCoolClass { public: MyCoolClass(int x, int y, int z): x(x), y(y), z(z), secretX(-1) {}; int x, y, z; private: MyCoolClass(); int secretX; SimpleClass enclosed; friend class cereal::access; };
#include <cereal/archives/json.hpp> #include "toto.hpp" MyCoolClass::MyCoolClass(): secretX(0), enclosed() { cereal::JSONOutputArchive archive(std::cout); archive(*this); }; template<class Archive> void save(Archive & archive, MyCoolClass const & m) { archive(m.x, m.y, m.z, m.secretX, m.enclosed); }; template<class Archive> void load(Archive & archive, MyCoolClass & m) { archive(m.x, m.y, m.z, m.secretX, m.enclosed); }; template<class Archive> void save(Archive & archive, SimpleClass const & m) { archive(m.date); }; template<class Archive> void load(Archive & archive, SimpleClass & m) { archive(m.date); };
You’ve given a specific class within cereal (cereal::access
) access to your member variables with the friend class cereal:;access
, but you try to access the member variables directly in the non-member save
function, which does not have access to the data. If you wanted this function to access those private members, you would need to have it explicitly listed as a friend as well. Check out the documentation of friend functions for more information.
C++: member (?) ‘is private within this context’
Problem:
Your Queue class is up and working in a customer service company. The company opens up a new branch and asks you to make another version of the Queue for them. The only difference is the way the Queue is displayed: each number on a new line.
You decide to create a new class called Queue2, which is derived from the Queue class and overrides the print() method, outputting each element of the queue on a new line.
Do not forget to change the access specifier of the Queue members, as they won’t be inherited if private.
Here is my code so far:
#include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void add(int data) { queue[size] = data; size++; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout << endl; } Queue operator+(Queue &obj) { Queue res; for(int i=0;i<this->size;i++) { res.add(this->queue[i]); } for(int i=0;i<obj.size;i++) { res.add(obj.queue[i]); } return res; } }; //your code goes here class Queue2 : public Queue { void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout << endl; } }; int main() { Queue q1; q1.add(42); q1.add(2); q1.add(8); q1.add(1); q1.print(); Queue2 q2; q2.add(3); q2.add(66); q2.add(128); q2.add(5);q2.add(111);q2.add(77890); q2.print(); return 0; }
But I’m getting, for instance…
/usercode/file0.cpp:54:7: error: ‘int Queue::size’ is private within this context
I understand that on lines 5 & 6 size
& queue
are effectively private, and I should instead access them through the public method Queue()
, right? But I don’t know how I can do that when surely I need them to make Queue()
work? Any help please?
Archived post. New comments cannot be posted and votes cannot be cast.
There are mainly 2 problems in your code, first, you are confusing static and non-static member variables and second, your last 3 functions are declared in the class declaration but you didn’t qualify them with Product::
so they are free standing functions with the same names. If you intended them to be the definitions of the members, qualify them.
To fix the first point, when you have a class like the following:
struct some_class
{
int nonstatic_member;
static int static_member;
}
You access the static ones using the TypeName::MemberName
syntax:
some_class::static_member = 5;
However, when a member is not static, you need an instance of that class to access the member:
some_class some_object;
some_object.nonstatic_member = 10;
The same rules apply for member functions as well:
void some_class::some_function()
{
some_class::nonstatic_member = 10; // error
this->nonstatic_member = 10; // fine
nonstatic_member = 10; // fine
static_member = 5; // fine
some_class::static_member = 5; // fine
}
Since none of your member variables are static, your use of Product::
everywhere is the cause of the second error.
If you’re not sure about the static member concept, here is a read: http://en.cppreference.com/w/cpp/language/static
I am attempting to create a queue, which requires the creation of another object stored in the queue. The errors are
binary.cpp: In function ‘int main()’:
binary.cpp:183:1: error: ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’ is private
Queue<T>::Queue(T item){
^
binary.cpp:286:65: error: within this context
Queue<binary<string>*>* queue = new Queue<binary<string>*>(tree);
^
and
binary.cpp: In instantiation of ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’:
binary.cpp:286:65: required from here
binary.cpp:132:1: error: ‘Link<T>::Link(T) [with T = binary<std::basic_string<char> >*]’ is private
Link<T>::Link(T item){
^
binary.cpp:184:7: error: within this context
head = new Link<T>(item);
The first is the instantiation of the Queue, and the second comes from the Queue’s constructor, which is called in the instantiation line in the first error. The important declarations and definitions are:
template<class T>
class Link{
Link(T item);
private:
T content;
Link<T>* next;
};
template<class T>
Link<T>::Link(T item){
content = item;
next = NULL;
}
template<class T>
class Queue{
Queue();
Queue(T item);
private:
Link<T>* head;
Link<T>* end;
int length;
};
template<class T>
Queue<T>::Queue(T item){
head = new Link<T>(item);
end = head;
length = 1;
}
The Link class is declared and defined before the Queue class, and both are declared and defined before they are used in code. Thank you for your time.
Содержание
- Error within this context is private
- compiler error: is private within this context
- 2 Answers 2
Below is the sample code that illustrates my problem.
The programs throws the following error:
error: ‘int test::Test::x’ is private within this context|
I have to put the class inside a namespace , it has to contain the operator overload and the variable must be private but I can’t seem to get it working.
The compiled is compiled in GCC 9.2.0, codeblocks, windows 10.
You are learning about name spaces, so now is the time to learn how to qualify what is in a name space be it «std::» or «test::». Stop relaying on the «using» statements.
Line 19 is not working the way that you are thinking is should. This does work for line 28.
In the following code there are two options. I suggest learning to use the first option as it will serve you better in the long run.
Choose option 1 or 2. It will not compile if you leave both. Either one works when tested with VS2017.
Since you put the class in a name space the functions defined outside the class either need to be qualified or put in the same name space.
It works, thank you very much.
But why exactly the choice 1 is better than the choice 2.
For me the choice 2 makes the code less verbose, it is quicker to use as choice 1 seems to be more readable and makes the code cleaner and clearer I think.
Because now that yo are learning about «name spaces» it is a good idea to learn how to qualify what is in a «name space» be it a «name space» that you define or what is in the «standard» namespace.
Given the line using namespace std; may seem to be easy to use right now, but some day it will cause you a problem. Whom ever taught you about this using statement is just lazy or the course was designed to to teach name spaces much later than it should be.
There may be times when splitting something in a name space that you define into two files it may be better to use option 2 to make everything work.
If you feel more comfortable using option 2 then do so. It is better to understand what you are doing first.
Actually you should be putting the function inside the same namespace as in choice 2, or place the implementation directly within the class.
Источник
compiler error: is private within this context
I’m writing a class and when I compile, I get one error message that says, «is private within this context» and another that says, «invalid use of non-static data member». But if I comment out everything before the addShipment function in my cpp file, it compiles just fine. Can someone please explain to me what is different to sometimes cause an error and sometimes not, and if the two different types of errors are related.
2 Answers 2
There are mainly 2 problems in your code, first, you are confusing static and non-static member variables and second, your last 3 functions are declared in the class declaration but you didn’t qualify them with Product:: so they are free standing functions with the same names. If you intended them to be the definitions of the members, qualify them.
To fix the first point, when you have a class like the following:
You access the static ones using the TypeName::MemberName syntax:
However, when a member is not static, you need an instance of that class to access the member:
The same rules apply for member functions as well:
Since none of your member variables are static, your use of Product:: everywhere is the cause of the second error.
If you’re not sure about the static member concept, here is a read: http://en.cppreference.com/w/cpp/language/static
The «private within this context» error refers to the fact that the functions addShipment , reduceInventory and getPrice are not members or friends of the class Product , so they cannot use its private members.
The «invalid use of non-static data member» error refers to the fact that you are trying to access non-static data members by qualifying them using the syntax Class::member , which is how you access static data members, which are shared by all instances of a class. Non-static data members are accessed using the syntax object.member or pointer->member , as separate instances of each data member exist for each instance of a class.
And I assume that you mean the errors disappear if you comment out everything after (and including) the addShipment function, rather than everything before it. This is because both kinds of error refer to code within the non-member functions.
Источник
No10 30 / 28 / 4 Регистрация: 03.06.2010 Сообщений: 465 |
||||||||||||||||
1 |
||||||||||||||||
Ошибки я не пойму что от меня хотят12.06.2012, 12:08. Показов 11128. Ответов 5 Метки нет (Все метки)
Есть 3 файла. main.cpp, array1.cpp и array1.h. Собственно такие ошибки
array1.cpp
array1.h
main.cpp
Схожу с ума не могу понять в чём же проблема.
__________________ 0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
12.06.2012, 12:08 |
Ответы с готовыми решениями: Задачка не пойму что хотят) Что от меня хотят? Что от меня хотят? Не могли бы вы объяснить его на русском языке. Что же от меня хотят? :] 5 |
2554 / 1319 / 178 Регистрация: 09.05.2011 Сообщений: 3,086 Записей в блоге: 1 |
|
12.06.2012, 12:27 |
2 |
Зачем мне компилятор говорит ‘int Array::size’ is private? Я знаю что она закрытая, изменить я её не пытаюсь, я её только считываю, причём функциями элементами 1) Путаете приватность и константность
Но самое глупая это within this context — вообще бред. Это еще почему? 1 |
30 / 28 / 4 Регистрация: 03.06.2010 Сообщений: 465 |
|
12.06.2012, 12:32 [ТС] |
3 |
within this context что за ошибка? 0 |
2554 / 1319 / 178 Регистрация: 09.05.2011 Сообщений: 3,086 Записей в блоге: 1 |
|
12.06.2012, 12:33 |
4 |
No10, вытягивайте английский. Within this context(В этом контексте) указывает на строку, которая вызывает ошибку 1 |
30 / 28 / 4 Регистрация: 03.06.2010 Сообщений: 465 |
|
12.06.2012, 12:36 [ТС] |
5 |
for (int i = 0; i < a.size; i++) какая здесь может быть ошибка? я то понял что он говорит что здесь ошибка но ничего подробней.. 0 |
2554 / 1319 / 178 Регистрация: 09.05.2011 Сообщений: 3,086 Записей в блоге: 1 |
|
12.06.2012, 12:39 |
6 |
Кроме той, о которой я указал — никаких. Есть ошибка с if, в которой i не определена. 0 |
Code for other’s reference:
#include <time.h> #include <cereal/access.hpp> class SimpleClass { public: explicit SimpleClass(struct tm const &); private: struct tm date; SimpleClass(); friend class MyCoolClass; friend class cereal::access; }; class MyCoolClass { public: MyCoolClass(int x, int y, int z): x(x), y(y), z(z), secretX(-1) {}; int x, y, z; private: MyCoolClass(); int secretX; SimpleClass enclosed; friend class cereal::access; };
#include <cereal/archives/json.hpp> #include "toto.hpp" MyCoolClass::MyCoolClass(): secretX(0), enclosed() { cereal::JSONOutputArchive archive(std::cout); archive(*this); }; template<class Archive> void save(Archive & archive, MyCoolClass const & m) { archive(m.x, m.y, m.z, m.secretX, m.enclosed); }; template<class Archive> void load(Archive & archive, MyCoolClass & m) { archive(m.x, m.y, m.z, m.secretX, m.enclosed); }; template<class Archive> void save(Archive & archive, SimpleClass const & m) { archive(m.date); }; template<class Archive> void load(Archive & archive, SimpleClass & m) { archive(m.date); };
You’ve given a specific class within cereal (cereal::access
) access to your member variables with the friend class cereal:;access
, but you try to access the member variables directly in the non-member save
function, which does not have access to the data. If you wanted this function to access those private members, you would need to have it explicitly listed as a friend as well. Check out the documentation of friend functions for more information.
Problem:
Your Queue class is up and working in a customer service company. The company opens up a new branch and asks you to make another version of the Queue for them. The only difference is the way the Queue is displayed: each number on a new line.
You decide to create a new class called Queue2, which is derived from the Queue class and overrides the print() method, outputting each element of the queue on a new line.
Do not forget to change the access specifier of the Queue members, as they won’t be inherited if private.
Here is my code so far:
#include <iostream>
using namespace std;
class Queue {
int size;
int* queue;
public:
Queue() {
size = 0;
queue = new int[100];
}
void add(int data) {
queue[size] = data;
size++;
}
void remove() {
if (size == 0) {
cout << "Queue is empty"<<endl;
return;
}
else {
for (int i = 0; i < size - 1; i++) {
queue[i] = queue[i + 1];
}
size--;
}
}
void print() {
if (size == 0) {
cout << "Queue is empty"<<endl;
return;
}
for (int i = 0; i < size; i++) {
cout<<queue[i]<<" <- ";
}
cout << endl;
}
Queue operator+(Queue &obj) {
Queue res;
for(int i=0;i<this->size;i++) {
res.add(this->queue[i]);
}
for(int i=0;i<obj.size;i++) {
res.add(obj.queue[i]);
}
return res;
}
};
//your code goes here
class Queue2 : public Queue {
void print() {
if (size == 0) {
cout << "Queue is empty"<<endl;
return;
}
for (int i = 0; i < size; i++) {
cout<<queue[i]<<" <- ";
}
cout << endl;
}
};
int main() {
Queue q1;
q1.add(42); q1.add(2); q1.add(8); q1.add(1);
q1.print();
Queue2 q2;
q2.add(3); q2.add(66); q2.add(128); q2.add(5);q2.add(111);q2.add(77890);
q2.print();
return 0;
}
But I’m getting, for instance…
/usercode/file0.cpp:54:7: error: ‘int Queue::size’ is private within this context
I understand that on lines 5 & 6 size
& queue
are effectively private, and I should instead access them through the public method Queue()
, right? But I don’t know how I can do that when surely I need them to make Queue()
work? Any help please?
- Forum
- Beginners
- Accessing private variables in friend me
Accessing private variables in friend methods from a class that is inside a namespace
Below is the sample code that illustrates my problem.
|
|
The programs throws the following error:
error: 'int test::Test::x' is private within this context|
I have to put the class inside a namespace
, it has to contain the operator<<
overload and the variable must be private but I can’t seem to get it working.
The compiled is compiled in GCC 9.2.0, codeblocks, windows 10.
Any help?
Thanks
Hello hbcpp,
You are learning about name spaces, so now is the time to learn how to qualify what is in a name space be it «std::» or «test::». Stop relaying on the «using» statements.
Line 19 is not working the way that you are thinking is should. This does work for line 28.
In the following code there are two options. I suggest learning to use the first option as it will serve you better in the long run.
|
|
Choose option 1 or 2. It will not compile if you leave both. Either one works when tested with VS2017.
Since you put the class in a name space the functions defined outside the class either need to be qualified or put in the same name space.
Andy
Hi Andy
It works, thank you very much.
But why exactly the choice 1 is better than the choice 2.
For me the choice 2 makes the code less verbose, it is quicker to use as choice 1 seems to be more readable and makes the code cleaner and clearer I think.
Hello hbcpp,
Because now that yo are learning about «name spaces» it is a good idea to learn how to qualify what is in a «name space» be it a «name space» that you define or what is in the «standard» namespace.
Given the line using namespace std;
may seem to be easy to use right now, but some day it will cause you a problem. Whom ever taught you about this using statement is just lazy or the course was designed to to teach name spaces much later than it should be.
There may be times when splitting something in a name space that you define into two files it may be better to use option 2 to make everything work.
If you feel more comfortable using option 2 then do so. It is better to understand what you are doing first.
Andy
Actually you should be putting the function inside the same namespace as in choice 2, or place the implementation directly within the class.
Choice 1 should fail to compile, from the online compiler:
21:63: error: ‘std::ostream& test::operator<<(std::ostream&, test::Test)’ should have been declared inside ‘test’
Noted Andy, thanks guys for the help, really appreciated it.
Topic archived. No new replies allowed.