Is private within this context c ошибка

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.

Содержание

  1. Error within this context is private
  2. compiler error: is private within this context
  3. 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. Собственно такие ошибки

C++
1
2
3
4
5
6
7
8
ivanarray1.h||In function 'std::ostream& operator<<(std::ostream&, Array&)':|
ivanarray1.h|27|error: 'int Array::size' is private|
ivanarray1.cpp|101|error: within this context|
ivanarray1.h|25|error: 'int* Array::ptr' is private|
ivanarray1.cpp|102|error: within this context|
ivanarray1.cpp|107|error: name lookup of 'i' changed for ISO 'for' scoping|
ivanarray1.cpp|107|note: (if you use '-fpermissive' G++ will accept your code)|
||=== Build finished: 5 errors, 0 warnings ===|

array1.cpp

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
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include "array1.h"
 
using namespace std;
 
int Array::arrayCount = 0;
// Конструктор с умолчанием класса Array
 
Array::Array(int ArraySize)
{
    ++arrayCount;
    size = ArraySize;
    ptr = new int[size];
    assert(ptr != 0);
 
    for (int i = 0; i < size; i++)
        ptr[i] = 0; //задание массиву начальных значений
 
}
 
Array::Array(const Array &init)
{
    ++arrayCount;
    size = init.size;
    ptr = new int[size];
    assert(ptr != 0);
 
    for (int i = 0; i < size; i++)
        ptr[i] = init.ptr[i];
}
 
Array::~Array()
{
    --arrayCount;
    delete [ ] ptr;
}
 
int Array::getSize() const { return size; }
 
// перегруженная операция присваивания
const Array &Array::operator=(const Array &right)
{
    if (&right != this) {
        delete [ ] ptr;
        size = right.size;
        ptr = new int[size];
        assert(ptr != 0);
 
        for (int i = 0; i < size; i++)
            ptr[i] = right.ptr[i];
    }
    return *this; // для = y = z = c
}
//перегрузка равенства двух массивов
//1 возвращает если равны и 0 если не равны
int Array::operator==(const Array &right) const
{
    if (size != right.size)
        return 0;
 
    for (int i = 0; i < size; i++)
        if (ptr[i] != right.ptr[i])
            return 0;
 
    return 1;
}
 
int Array::operator!=(const Array &right) const
{
    if (size != right.size)
        return 1;
 
    for (int i = 0; i < size; i++)
        if (ptr[i] != right.ptr[i])
            return 1;
 
    return 0;
}
 
int &Array::operator[](int subscript)
{
    assert(0 <= subscript && subscript < size);
 
    return ptr[subscript];
}
 
int Array::getArrayCount() { return arrayCount; }
 
istream &operator>> (istream &input, Array &a)
{
    for (int i = 0; i < a.size; i++)
        input >> a.ptr[i];
 
    return input;
}
 
ostream &operator<< (ostream &output, Array &a)
{
    for (int i = 0; i < a.size; i++) {
        output << a.ptr[i] << " ";
 
        if ((i + 1) % 10 == 0)
            output << endl;
    }
    if (i % 10 == 0)
        output << endl;
 
    return output;
}

array1.h

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
#ifndef ARRAY1_H
#define ARRAY1_H
 
#include <iostream>
 
using namespace std;
 
class Array {
        friend ostream &operator<< (ostream &, const Array &);
        friend istream &operator>> (istream &, Array &);
    public:
        Array(int = 10);
        Array(const Array &);
        ~Array();
        int getSize() const;
        const Array &operator=(const Array &);
 
        int operator==(const Array &) const;
        int operator!=(const Array &) const;
 
        int &operator[](int); // операция индексации
        static int getArrayCount(); // возращение числа экземпляров
 
    private:
        int *ptr;
 
        int size;
        static int arrayCount;
 
};
 
#endif // ARRAY1_H

main.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>
#include <windows.h>
#include <math.h>
#include "array1.h"
 
using namespace std;
 
char bufRus[256];
char* Rus(const char* text) {
      CharToOem(text, bufRus);
      return bufRus;
      }
 
 
int main()
{
    cout << Rus("Колличество созданных массивов: ")
         << Array::getArrayCount() << endl;
 
    system("pause");
    return 0;
}

Схожу с ума не могу понять в чём же проблема.
Зачем мне компилятор говорит ‘int Array::size’ is private? Я знаю что она закрытая, изменить я её не пытаюсь, я её только считываю, причём функциями элементами. Что здесь не так? Но самое глупая это within this context — вообще бред.

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

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

12.06.2012, 12:08

Ответы с готовыми решениями:

Задачка не пойму что хотят)
Условие
Задание 1 – создание метода списком аргументов и возвращаемым значением.
Требуется…

Что от меня хотят?
Вам предстоит сделать свой первый сайт,
пока пустой! На любом хостинге, хоть платном, хоть…

Что от меня хотят?
Дали такое тестовое:

Не могли бы вы объяснить его на русском языке.
Возможно я его смогу…

Что же от меня хотят? :]
только только разобрался с бинарным деревом и получил вот такое новое задание но что то не совсем…

5

2554 / 1319 / 178

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

Сообщений: 3,086

Записей в блоге: 1

12.06.2012, 12:27

2

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

Зачем мне компилятор говорит ‘int Array::size’ is private? Я знаю что она закрытая, изменить я её не пытаюсь, я её только считываю, причём функциями элементами

1) Путаете приватность и константность
2) Функция описана с константным аргументом, а реализация с не-константным.

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

Но самое глупая это 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.

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
#include <iostream>
#include <ostream>

using namespace std;

namespace test
{
class Test
{
    int x;
public:
    Test(int n) : x(n) {}

    friend ostream& operator<< (ostream& os, const Test t);
};

}

using namespace test;
ostream& operator<< (ostream& os, const Test t)
{
    os << t.x;
    return os;
}

int main()
{
    Test g(3);

    cout << g;


    return 0;
}  

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.

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
#include <iostream>
//#include <ostream> // <--- included in "iostream".

//using namespace std;  // <--- Best not to use.
// The most recent post that is worth reading. http://www.cplusplus.com/forum/beginner/258335/


namespace test
{
	class Test
	{
			int x;
		public:
			Test(int n) : x(n) {}

			friend std::ostream& operator<< (std::ostream& os, const Test t);
	};

}

std::ostream& test::operator<< (std::ostream& os, const Test t) // <--- Option 1. Better choice.
{
	os << t.x;
	return os;
}

namespace test // <--- Option 2.
{
	std::ostream& operator<< (std::ostream& os, const Test t)
	{
		os << t.x;
		return os;
	}
}

//using namespace test;

int main()
{
	//Test g(3);
	test::Test g(3); // <--- Better choice.
	std::cout << g;


	return 0;  // <--- Not required, but makes a good break point.
}

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.

Понравилась статья? Поделить с друзьями:
  • Is not a block device ошибка монтирования
  • Is mf03 5 ошибка при удалении
  • Is mf02 5 ошибка gta v
  • Is lulu is in the garden где ошибка
  • Is fc05 файл поврежден код ошибки