My problem is that i want to create multiple instances of my upgrade class, for different upgrades. Maybe it's because i'm used to java but i can't just type Source first("first"), second("second");
because if i do and call first.getName()
for example, i get "second"
. I made an example file where i only wrote what i'm struggling with, so you don't have to try to understand my mess of a code.
Source.cpp: I want multiple instances of this class.
#include "Source.h" std::string name; Source::Source() { } Source::Source(std::string nameToSet) { name = nameToSet; } std::string Source::getName() { return name;
Source.h
#pragma once #includeclass Source { public: Source(); Source(std::string namel); std::string getName(); };
Test.cpp
#include "Source.h" #include "iostream" Source first("first"), second("second"); int main() { std::cout << first.getName() << std::endl; }
Output: second
Test.h
#pragma once #include
Code-Apprent.. 9
The problem is with this line:
std::string name;
This declares a single global string named name
. This variable is not associated with any Source
instance. Instead, you need to declare a field inside the Source
class:
class Source { public: Source(); Source(std::string namel); std::string getName(); // Add these two lines private: std::string name; };
This will give a name
for each Source
. I suggest you study about class fields and the differences between public
and private
access.
The problem is with this line:
std::string name;
This declares a single global string named name
. This variable is not associated with any Source
instance. Instead, you need to declare a field inside the Source
class:
class Source { public: Source(); Source(std::string namel); std::string getName(); // Add these two lines private: std::string name; };
This will give a name
for each Source
. I suggest you study about class fields and the differences between public
and private
access.