Equal operator attempting to reference a deleted function, array - c++

I am using SFML to create a space invaders clone with C++. I am quite new to C++ and I'm learning it as I'm working on this project.
I am getting the following error when trying to create a new enemy using the constructor and array to set settings for each created enemy:
1>enemy.cpp
1>C:\Users\dzamm\source\repos\SFML\enemy.cpp(35,1): error C2280: 'Enemy &Enemy::operator =(const Enemy &)': attempting to reference a deleted function
1>C:\Users\dzamm\source\repos\SFML\enemy.h(55): message : compiler has generated 'Enemy::operator =' here
1>C:\Users\dzamm\source\repos\SFML\enemy.h(55,1): message : 'Enemy &Enemy::operator =(const Enemy &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'sf::RenderWindow &sf::RenderWindow::operator =(const sf::RenderWindow &)'
Enemy Constructor:
Enemy alienArray[NUMBER_OF_ALIENS];
//constructor sets ID number, loads sprite
Enemy::Enemy(const int id, float sp)
{
//set alive
mIsAlive = true;
//set speed
enemySpeed = sp;
// Load an enemy texture
if (!mEnemyTexture.loadFromFile("Media/Textures/PixelSpaceships/red_01.png")) {
// Handle loading error
std::cout << "Oh No! File not loaded." << std::endl;
}
//scale sprite and set texture so we know size
enemySprite.setTexture(mEnemyTexture);
}
Enemy loader method
void Enemy::loader(int noOfAliens) { // might add xPosition;yPosition
for (int i = 0; i < noOfAliens; i++)
{
Enemy alien(i, 10.f); // speed issue
alien.setLocation(i * 100.f + 50.f, alien.getSprite().getGlobalBounds().height / 2);
line 35 alienArray[i] = alien;
//alienArray.push_back(alien);
}
}
1>C:\Users\dzamm\source\repos\SFML\enemy.cpp(35,1): error C2280: 'Enemy &Enemy::operator =(const Enemy &)': attempting to reference a deleted function
Enemy Header file:
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#pragma once
#define NUMBER_OF_ALIENS 4
//class Game;
class Enemy
{
public:
//constructor sets ID number, loads sprite
Enemy() {};
Enemy(const int, float);
sf::Sprite& getSprite();
void kill();
bool isAlive();
void load();
void loader(const int noOfAliens);
void setLocation(float xPosition, float yPosition);
void enemyInstantiator(int noOfEnemies, float xPosition, float yPosition);
void update();
void render(sf::RenderWindow& window);
private:
void enemyBehaviour(std::vector<sf::Sprite>& enemyList);
void enemyMovement(std::vector<Enemy>& enemyList);
private:
sf::Texture mEnemyTexture;
sf::Sprite enemySprite;
//std::vector<Enemy> alienArray;
//std::vector<sf::Sprite> mEnemies;
sf::RectangleShape mEnemyBounds;
sf::RenderWindow mWindow;
bool mIsShooting;
bool mIsAlive;
float enemySpeed;
};
I read on forums that issue is related to working with a copy of the object instead of the original object, however I am not sure how to handle this to reference the original object I'm modifying.
To reproduce create a constructor for Enemy.cpp class, create an entity Enemy alien using for loop in method as shown in Enemy::loader and store the created entity in the Enemy alienArray as shown by index.

The issue was related to an sf::RenderWindow reference that was not being even utilised in the code.
sf::RenderWindow &sf::RenderWindow::operator =(const sf::RenderWindow &)
Once I removed this all errors disappeared.

Related

I keep getting errors for UE4 FPS Section 3.1 tutorial. What should I do?

For the following codes I'm supposed to add a projectile and be able to fire it yet the lines of code provided by UE4 to do so don't compile. Whenever I compile, it gives me multiple error codes. Below are the codes used for this project.
FPSProjectile.h
#pragma once
#include "GameFramework/Actor.h"
#include "FPSProjectile.generated.h"
UCLASS()
class FPSPROJECT_API AFPSProjectile : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AFPSProjectile();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Sphere collision component.
UPROPERTY(VisibleDefaultsOnly, Category = Projectile)
USphereComponent* CollisionComponent;
// Projectile movement component.
UPROPERTY(VisibleAnywhere, Category = Movement)
UProjectileMovementComponent* ProjectileMovementComponent;
// Function that initializes the projectile's velocity in the shoot direction.
void FireInDirection(const FVector& ShootDirection);
};
FPSCharacter.cpp
#include "FPSProject.h"
#include "FPSCharacter.h"
// Sets default values
AFPSCharacter::AFPSCharacter()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Create a first person camera component.
FPSCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));
// Attach the camera component to our capsule component.
FPSCameraComponent->SetupAttachment(GetCapsuleComponent());
// Position the camera slightly above the eyes.
FPSCameraComponent->SetRelativeLocation(FVector(0.0f, 0.0f, 50.0f + BaseEyeHeight));
// Allow the pawn to control camera rotation.
FPSCameraComponent->bUsePawnControlRotation = true;
// Create a first person mesh component for the owning player.
FPSMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FirstPersonMesh"));
// Only the owning player sees this mesh.
FPSMesh->SetOnlyOwnerSee(true);
// Attach the FPS mesh to the FPS camera.
FPSMesh->SetupAttachment(FPSCameraComponent);
// Disable some environmental shadowing to preserve the illusion of having a single mesh.
FPSMesh->bCastDynamicShadow = false;
FPSMesh->CastShadow = false;
// The owning player doesn't see the regular (third-person) body mesh.
GetMesh()->SetOwnerNoSee(true);
}
// Called when the game starts or when spawned
void AFPSCharacter::BeginPlay()
{
Super::BeginPlay();
if (GEngine)
{
// Put up a debug message for five seconds. The -1 "Key" value (first argument) indicates that we will never need to update or refresh this message.
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("We are using FPSCharacter."));
}
}
// Called every frame
void AFPSCharacter::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
// Called to bind functionality to input
void AFPSCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
// Set up "movement" bindings.
PlayerInputComponent->BindAxis("MoveForward", this, &AFPSCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AFPSCharacter::MoveRight);
// Set up "look" bindings.
PlayerInputComponent->BindAxis("Turn", this, &AFPSCharacter::AddControllerYawInput);
PlayerInputComponent->BindAxis("LookUp", this, &AFPSCharacter::AddControllerPitchInput);
// Set up "action" bindings.
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AFPSCharacter::StartJump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &AFPSCharacter::StopJump);
PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AFPSCharacter::Fire);
}
void AFPSCharacter::MoveForward(float Value)
{
// Find out which way is "forward" and record that the player wants to move that way.
FVector Direction = FRotationMatrix(Controller->GetControlRotation()).GetScaledAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
void AFPSCharacter::MoveRight(float Value)
{
// Find out which way is "right" and record that the player wants to move that way.
FVector Direction = FRotationMatrix(Controller->GetControlRotation()).GetScaledAxis(EAxis::Y);
AddMovementInput(Direction, Value);
}
void AFPSCharacter::StartJump()
{
bPressedJump = true;
}
void AFPSCharacter::StopJump()
{
bPressedJump = false;
}
void AFPSCharacter::Fire()
{
}
FPSCharacter.h
#pragma once
#include "GameFramework/Character.h"
#include "FPSCharacter.generated.h"
UCLASS()
class FPSPROJECT_API AFPSCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AFPSCharacter();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// Handles input for moving forward and backward.
UFUNCTION()
void MoveForward(float Value);
// Handles input for moving right and left.
UFUNCTION()
void MoveRight(float Value);
// Sets jump flag when key is pressed.
UFUNCTION()
void StartJump();
// Clears jump flag when key is released.
UFUNCTION()
void StopJump();
// Function that handles firing projectiles.
UFUNCTION()
void Fire();
// FPS camera.
UPROPERTY(VisibleAnywhere)
class UCameraComponent* FPSCameraComponent;
// First-person mesh (arms), visible only to the owning player.
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
USkeletalMeshComponent* FPSMesh;
// Gun muzzle's offset from the camera location.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
FVector MuzzleOffset;
// Projectile class to spawn.
UPROPERTY(EditDefaultsOnly, Category = Projectile)
TSubclassOf<class AFPSProjectile> ProjectileClass;
};
FPSProjectile.cpp
#include "FPSProject.h"
#include "FPSProjectile.h"
// Sets default values
AFPSProjectile::AFPSProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Use a sphere as a simple collision representation.
CollisionComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
// Set the sphere's collision radius.
CollisionComponent->InitSphereRadius(15.0f);
// Set the root component to be the collision component.
RootComponent = CollisionComponent;
// Use this component to drive this projectile's movement.
ProjectileMovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovementComponent"));
ProjectileMovementComponent->SetUpdatedComponent(CollisionComponent);
ProjectileMovementComponent->InitialSpeed = 3000.0f;
ProjectileMovementComponent->MaxSpeed = 3000.0f;
ProjectileMovementComponent->bRotationFollowsVelocity = true;
ProjectileMovementComponent->bShouldBounce = true;
ProjectileMovementComponent->Bounciness = 0.3f;
}
// Called when the game starts or when spawned
void AFPSProjectile::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AFPSProjectile::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
// Function that initializes the projectile's velocity in the shoot direction.
void AFPSProjectile::FireInDirection(const FVector& ShootDirection)
{
ProjectileMovementComponent->Velocity = ShootDirection * ProjectileMovementComponent->InitialSpeed;
}
The following is the errors I get
error "FPSCharacter.generated.h already included, missing '#pragma once' in FPSCharacter.h"
^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.cpp:16:23: error: member access into incomplete type 'class UCameraComponent' FPSCameraComponent->SetupAttachment(GetCapsuleComponent()); ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.h:50:11: note: forward declaration of 'UCameraComponent' class UCameraComponent* FPSCameraComponent; ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.cpp:18:23: error: member access into incomplete type 'class UCameraComponent' FPSCameraComponent->SetRelativeLocation(FVector(0.0f, 0.0f, 50.0f + BaseEyeHeight)); ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.h:50:11: note: forward declaration of 'UCameraComponent' class UCameraComponent* FPSCameraComponent; ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.cpp:20:23: error: member access into incomplete type 'class UCameraComponent' FPSCameraComponent->bUsePawnControlRotation = true; ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.h:50:11: note: forward declaration of 'UCameraComponent' class UCameraComponent* FPSCameraComponent; ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSCharacter.cpp:27:30: error: cannot initialize a parameter of type 'USceneComponent ' with an lvalue of type 'class UCameraComponent ' FPSMesh->SetupAttachment(FPSCameraComponent); ^~~~~~~~~~~~~~~~~~ /Users/apple/UE_4.25/Engine/Source/Runtime/Engine/Classes/Components/SceneComponent.h:653:40: note: passing argument to parameter 'InParent' here void SetupAttachment(USceneComponent InParent, FName InSocketName = NAME_None); ^ In file included from /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.cpp:4: /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.h:27:5: error: unknown type name 'USphereComponent' USphereComponent CollisionComponent; ^ In file included from /Users/apple/Documents/Unreal Projects/FPSProject/Intermediate/Build/Mac/UE4Editor/Inc/FPSProject/FPSProjectile.gen.cpp:8: /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.h:27:5: error: unknown type name 'USphereComponent' USphereComponent* CollisionComponent; ^ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.h:31:5: error: unknown type name 'UProjectileMovementComponent'; did you mean 'UPawnMovementComponent'? UProjectileMovementComponent* ProjectileMovementComponent; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ UPawnMovementComponent /Users/apple/UE_4.25/Engine/Source/Runtime/Engine/Classes/GameFramework/Pawn.h:23:7: note: 'UPawnMovementComponent' declared here class UPawnMovementComponent; ^ In file included from /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.cpp:4: /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.h:11:5: error: cannot initialize return object of type 'UObject *' with an rvalue of type 'AFPSProjectile *' GENERATED_BODY() ^~~~~~~~~~~~~~~~ /Users/apple/UE_4.25/Engine/Source/Runtime/CoreUObject/Public/UObject/ObjectMacros.h:616:29: note: expanded from macro 'GENERATED_BODY'
define GENERATED_BODY(...) BODY_MACRO_COMBINE(CURRENT_FILE_ID,_,LINE,_GENERATED_BODY);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/apple/UE_4.25/Engine/Source/Runtime/CoreUObject/Public/UObject/ObjectMacros.h:611:37: note: expanded from macro 'BODY_MACRO_COMBINE'
define BODY_MACRO_COMBINE(A,B,C,D) BODY_MACRO_COMBINE_INNER(A,B,C,D)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/apple/UE_4.25/Engine/Source/Runtime/CoreUObject/Public/UObject/ObjectMacros.h:610:43: note: expanded from macro 'BODY_MACRO_COMBINE_INNER'
define BODY_MACRO_COMBINE_INNER(A,B,C,D) A##B##C##D
^~~~~~~~~~
note: (skipping 1 expansions in backtrace; use -fmacro-backtrace-limit=0 to see all) /Users/apple/Documents/Unreal Projects/FPSProject/Intermediate/Build/Mac/UE4Editor/Inc/FPSProject/FPSProjectile.generated.h:82:2: note: expanded from macro 'FPSProject_Source_FPSProject_FPSProjectile_h_11_GENERATED_BODY' FPSProject_Source_FPSProject_FPSProjectile_h_11_ENHANCED_CONSTRUCTORS \ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Users/apple/Documents/Unreal Projects/FPSProject/Intermediate/Build/Mac/UE4Editor/Inc/FPSProject/FPSProjectile.generated.h:56:58: note: expanded from macro 'FPSProject_Source_FPSProject_FPSProjectile_h_11_ENHANCED_CONSTRUCTORS' DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AFPSProjectile); \ ^ /Users/apple/UE_4.25/Engine/Source/Runtime/CoreUObject/Public/UObject/ObjectMacros.h:1588:11: note: expanded from macro '\ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER' return new (EC_InternalUseOnlyConstructor, (UObject*)GetTransientPackage(), NAME_None, RF_NeedLoad | RF_ClassDefaultObject | RF_TagGarbageTemp) TClass(Helper); \ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Users/apple/Documents/Unreal Projects/FPSProject/Source/FPSProject/FPSProjectile.h:31:5: error: unknown type name 'UProjectileMovementComponent'; did you mean 'UPawnMovementComponent'? UProjectileMovementComponent* ProjectileMovementComponent; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ UPawnMovementComponent /Users/apple/UE_4.25/Engine/Source/Runtime/Engine/Classes/GameFramework/Pawn.h:23:7: note: 'UPawnMovementComponent' declared here class UPawnMovementComponent; ^

unique_ptr<> causes compliation errors in C++

I am using this library: https://github.com/Agamnentzar/bluetooth-serial-port
BTSerialPortBinding::Create(address, channelID)
Returns new instance of BTSerialPortBinding object
address: string containint bluetooth address of the device
channelID: ID of the serial port channel
I have a statement:
unique_ptr<BTSerialPortBinding>bt(BTSerialPortBinding::Create(d1.address, 1));
When I separate the statement with the declaration in ArduinoDevice.h and initialisation in ArduinoDevice.cpp in constructor like so:
std::unique_ptr<BTSerialPortBinding> bt;
bt.reset(BTSerialPortBinding::Create("93:83:, 1));
When I added these statements I got the following error:
ArduinoDevice &ArduinoDevice::operator =(const ArduinoDevice &)': attempting to reference a deleted function
Relevant bit in Process.cpp file which is referenced by the error
dev = ArduinoDevice("/dev/tty.IP-DevB");
Process.h
#ifndef __PROCESS_H
#define __PROCESS_H
#define _USE_MATH_DEFINES
#include "ResonantLowpassFilter.h"
#include "ArduinoDevice.h"
//==============================================================================
/**
*/
class AudioProcessor : public AudioProcessor
{
public:
//==============================================================================
WahwahAudioProcessor();
~WahwahAudioProcessor();
void prepareToPlay (double sampleRate, int samplesPerBlock);
void releaseResources();
void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
AudioProcessorEditor* createEditor();
int getNumParameters();
int getNumPrograms();
int getCurrentProgram();
void setCurrentProgram (int index);
const String getProgramName (int index);
void changeProgramName (int index, const String& newName);
float centreFrequency_, q_;
void updateFilterArduino();
ArduinoDevice dev; //instance to an Arduino device from which sensor data is read
};
#endif // _PROCESS
ArduinoDevice.h
#ifndef ArduinoDevice_h
#define ArduinoDevice_h
#include <stdio.h>
#include "BTSerialPortBinding.h"
#include <memory>
class ArduinoDevice
{
public:
ArduinoDevice(const char *dev="");
void connect();
void start(void);
void stop(void);
void read(void);
/**
Disconnects from Arduino device
**/
~ArduinoDevice();
private:
const char *device; //port address of the device (e.g. "/dev/tty.FireFly-E552-SPP")
std::unique_ptr<BTSerialPortBinding> bt; //bt serial port
void close(void);
};
#endif
Edit:
I am using Windows 10, Visual Studio 2015 and Microsoft's C++ Compiler. I am also using an extra JUCE library(https://www.juce.com/).
dev = ArduinoDevice("/dev/tty.IP-DevB"));
dev is declared in the Process.h file above its an instance of ArduinoDevice
My constructor looks like this:
ArduinoDevice::ArduinoDevice(const char *dev)
{
device = dev;
bt.reset(BTSerialPortBinding::Create("98:D3:31:FD:11:1A", 1));
}
I've now tried this in ArduinoDevice.cpp and declaration .h but I still get the same error as above:
ArduinoDevice&&(const char *dev);
{
data = dev.data;
dev.data = nullptr;
}
unique_ptr is not copyable. So when you declare it as a member of your class, your class becomes non-copyable too. The error exactly points that out. (Copy assignment operator is deleted because of that).
Note that usually the move assignment operator is automatically generated by the compiler for you. But in your case since you've explicitly defined a destructor for your class, compiler cant safely define a move assignment operator (or constructor) for you.

base operand of ‘->’ has non-pointer type error

I got the error
" src/Graphics.cpp:29:32: erreur: base operand of ‘->’ has non-pointer type ‘std::vector’
"
on the following code :
Constructor :
Graphics::Graphics()
{
this->app = new sf::RenderWindow(sf::VideoMode(800, 800, 32), "La Zapette !",
sf::Style::Close | sf::Style::Titlebar);
sf::Image img;
img.LoadFromFile("./res/grass.jpg");
for (int i = 0; i != 16; i++)
{
this->map.push_back(new sf::Sprite());
this->map.back()->SetImage(img);
this->map.back()->SetPosition(sf::Vector2f(0, 50 * i));
this->app->Draw(this->map->back());
}
this->app->Display();
}
Class :
class Graphics
{
private:
sf::RenderWindow *app;
std::vector<sf::Sprite*> map;
public:
Graphics();
~Graphics();
Event getEvent();
};
When i put a dot instead an arrow after the .back() method it doesnt compile.
Thanks
This:
this->app->Draw(this->map->back());
Should be:
this->app->Draw(*(this->map.back()));
map is a vector, so its members should be accessed with . instead of ->.
Draw takes a const Drawable&, so the pointer in the vector should be dereferenced.
It is extremely helpful to post full error messages and examples that other folks can compile on their own machines.
#include <string>
#include <vector>
namespace sf {
struct Image {
void LoadFromFile(std::string);
};
struct Vector2f {
Vector2f(float, float);
};
struct VideoMode {
VideoMode(unsigned, unsigned, unsigned);
};
struct Sprite {
void SetImage(Image);
void SetPosition(Vector2f);
};
struct Style {
static const unsigned Close = 1;
static const unsigned Titlebar = 2;
};
struct RenderWindow {
RenderWindow(VideoMode, std::string, unsigned);
void Draw(Sprite *);
void Display();
};
}
class Event {
};
class Graphics
{
private:
sf::RenderWindow *app;
std::vector<sf::Sprite*> map;
public:
Graphics();
~Graphics();
Event getEvent();
};
Graphics::Graphics()
{
this->app = new sf::RenderWindow(sf::VideoMode(800, 800, 32), "La Zapette !",
sf::Style::Close | sf::Style::Titlebar);
sf::Image img;
img.LoadFromFile("./res/grass.jpg");
for (int i = 0; i != 16; i++)
{
this->map.push_back(new sf::Sprite());
this->map.back()->SetImage(img);
this->map.back()->SetPosition(sf::Vector2f(0, 50 * i));
this->app->Draw(this->map->back());
}
this->app->Display();
}
This code produces the error:
c++ foo.cc -o foo
foo.cc:61:34: error: member reference type 'std::vector<sf::Sprite *>' is not a pointer; maybe you meant
to use '.'?
this->app->Draw(this->map->back());
~~~~~~~~~^~
.
1 error generated.
make: *** [foo] Error 1
Notice that the error message has included the line that the error is on. This is very helpful because you certainly didn't post 29 lines of code.
Depending on the signature of Draw(), this line should be one of:
this->app->Draw(this->map.back());
this->app->Draw(*(this->map.back()));

qualifiers dropped in binding reference of type & to initializer of type const

I do not understand this error & cannot find any information on it.
#ifndef GAME_H
#define GAME_H
#include <SFML/System.hpp>
#include <cmath>
#include "Submarine.h"
#include "Obstacle.h"
class Game : public Submarine
{
public:
Game(unsigned w,unsigned h,bool g);
void setKey(char Key='n');
void update(float dt);
void Render (const RenderWindow &Window) const ;
static bool Collision(sf::Sprite& object1, sf::Sprite& object2);
unsigned getWidth();
unsigned getHeight();
char getKey();
protected:
bool newGame;
unsigned width;
unsigned height;
char currentInput;
};
#endif
The error occurring here;
void Game::Render(const RenderWindow &Window) const
{
sf::Sprite::Render(Window);
}
Error 27 error C2664: 'sf::Sprite::Render' : cannot convert parameter 1 from 'const sf::RenderWindow' to 'sf::RenderTarget &'
sf::Sprite::Render takes a reference to non-const while Window is a reference to const. C++ does not allow such binding, simple as that. It would break const-correctnes.
You'll probably want to take the parameter as RenderWindow&.

How to use an existing class for a new duty

The problem says:
Define a class Arc, which draws a part of an ellipse. Hint: fl_arc().
Ellipse is predefined class which draws an ellipse on the window by a statement, e.g., Ellipse e1(Point(200,200),50,50);
and fl_arc() is part of FLTK which I've previously installed it on my Windows machine.
Since the problem has wanted to draw a part of an ellipse by creating a new class named Arc, I think I should make a new class with that name and also use the definition of the class Ellipse and modify it so that it shows a part of an ellipse instead of whole of an ellipse as wanted. This problem is in Programming Principle and practice using C++ book and the only definition that I found in that book about the Ellipse class was this:
struct Ellipse :Shape {
Ellipse(Point p, int w, int h); //center, max and min distance from center
void draw_lines()const;
Point center()const;
Point focus1()const;
Point focus2()const;
void set_major(int ww) {w=ww;}
int major() const {return w;}
void set_minor(int hh) {h=hh;}
int minor() const {return h;}
private:
int w;
int h;
};
and also I found a case of using the fl_arc() in the book which was used for drawing a Circle like this:
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
Here r is radius.
So on my think, I changed the parameters of the fl_arc() and wrote the bellow code to give me what the problem has wanted:
#include <Simple_window.h>
struct arc : Shape {
arc(Point p, int w, int h) // center, min, and max distance from center
: w(w), h(h)
{
add(Point(p.x-w,p.y-h));
}
void draw_lines() const {fl_arc(point(0).x,point(0).y,w+w,h+h,0,120);}
Point center() const { return Point(point(0).x+w,point(0).y+h); }
Point focus1() const { return Point(center().x+int(sqrt(double(w*w-h*h))),center().y); }
Point focus2() const { return Point(center().x-int(sqrt(double(w*w-h*h))),center().y); }
void set_major(int ww) { w=ww; }
int major() const { return w; }
void set_minor(int hh) { h=hh; }
int minor() const { return h; }
private:
int w;
int h;
};
int main()
{
using namespace Graph_lib;
Point t(100,100);
Simple_window win(t,600,400, "semi-ellipse");
arc a(Point(200,200),150,50);
a.draw_lines();
win.wait_for_button();
}
The code runs successfully fortunately but it doesn't show any part of an ellipse.
Question:
Does anyone know why?
PS: If we can find some way for modifying a class we can tell that new class to does some new work for us.
Here is one possible implementation, where you use the already existing facilities of class Ellipse, overwriting the function draw_lines(), to define the class Arc:
#include"Simple_window.h"
#include"Graph.h"
#include<iostream>
using namespace Graph_lib;
//---------------------------------------------------------------------------
//Class Arc
namespace Graph_lib{
class Arc : public Ellipse {
public:
Arc(Point p, int w, int h, int arc_n, int arc_x) : Ellipse(p,w,h), arc_min(arc_n), arc_max(arc_x) {}
void draw_lines() const;
private:
int arc_min;
int arc_max;
};
void Arc::draw_lines() const
{
if(color().visibility())
fl_arc(point(0).x,point(0).y, major()*2, minor()*2, arc_min, arc_max);
}
}
//---------------------------------------------------------------------------
int main()
try
{
Simple_window win(Point(100,100), 800, 600, "Exercise #1");
Graph_lib::Arc arc1(Point(100,100),50,50,0,90);
win.attach(arc1);
win.wait_for_button();
}
catch(exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "unknown error..." << std::endl;
return 2;
}
Programming - Principles and Practice Using C++ (pg.477, exercise 1)
solution by Francisco Tavares
Although I could to find the bug of that code but still I have some issues about that exercise that I like to mention them among you professional guys.
If the line a.draw_lines(); will be replaced by this line win.attach(a); the problem runs successfully.
The remained problems are these:
1- Now when I use the name "Arc" instead of the "arc" in above code I get this error.
Error 8 error C2146: syntax error : missing ';' before identifier 'a' c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 25
Error 10
error C3861: 'a': identifier not found c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 25
2- The problem has wanted us to define a class (not a struct) so when I replace struct with class and put keyword public just after class arc : Shape {, I get this error.
*Error 8 error C2243: 'type cast' : conversion from 'arc *' to 'Graph_lib::Shape &' exists, but is inaccessible c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 29
Error 9 error C2243: 'type cast' : conversion from 'arc ' to 'Graph_lib::Shape &' exists, but is inaccessible c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 30
Any idea?