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.

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.

Product.h:

#ifndef PRODUCT_H
#define PRODUCT_H

#include <iostream>

class Product {
    public:
        Product(int productID, std::string productName);
        std::string getDescription();
        void setDescription(std::string description);
        std::string getName();
        int getID();
        int getNumberSold();
        double getTotalPaid();
        int getInventoryCount();
        void addShipment(int shipmentQuantity, double shipmentCost);
        void reduceInventory(int purchaseQuantity);
        double getPrice();
    private:
        int productID;
        std::string name;
        std::string description;
        double totalPaid;
        int inventoryCount;
        int numSold;
};

#endif

Product.cpp:

#include <iostream>
#include "Product.h"
using namespace std;

Product::Product(int productID, string productName) {
    Product::productID = productID;
    Product::name = productName;
}

string Product::getDescription() {
    return Product::description;
}

void Product::setDescription(string description) {
    Product::description = description;
}

string Product::getName() {
    return Product::name;
}

int Product::getID() {
    return Product::productID;
}

int Product::getNumberSold() {
    return Product::numSold;
}

double Product::getTotalPaid() {
    if(Product::totalPaid < 1) {
        totalPaid = 0;
    }
    return Product::totalPaid;
}

int Product::getInventoryCount() {
    Product::inventoryCount = 0; 
    return Product::inventoryCount;
}

void addShipment(int shipmentQuantity, double shipmentCost) {
    Product::inventoryCount = Product::inventoryCount + shipmentQuantity;
    Product::totalPaid = Product::totalPaid + shipmentCost;
}

void reduceInventory(int purchaseQuantity) {
    Product::inventoryCount = Product::inventoryCount - purchaseQuantity;
    Product::numSold = Product::numSold + purchaseQuantity;
}

double getPrice() {
    int price = (Product::totalPaid / static_cast<double>(Product::inventoryCount + Product::numSold)) * 1.25;
    return price;
}

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.

Понравилась статья? Поделить с друзьями:
  • Is not a valid integer value как исправить ошибку
  • Is not a valid database ошибка
  • Is not a function ошибка json
  • Is not a function javascript в чем ошибка
  • Is not a block device ошибка монтирования